Militant groups clash in NW Pakistan, 40 killed