Layer Specialization Underlying Compositional Reasoning in Transformers