Due to small size, the ionization enthalpies of Be and Mg are much higher than those of other alkaline earth metals. Therefore, a large amount of energy is needed to excite their valence electron and that’s why they do not impart colour to the flame.