How Diffusion Models Learn to Factorize and Compose