The shape memory effect (SME) occurs because a temperature-induced phase transformation reverses deformation, as shown in the previous hysteresis curve. Typically the martensitic phase is monoclinic or orthorhombic (B19' or [https://www.atomic-scale-physics.de/lattice/struk/b19.html B19]). Since these crystal structures do not have enough slip systems for easy dislocation motion, they deform by twinning—or rather, detwinning.
Martensite is thermodynamically favored at lower temperatures, while austenite ([https://www.atomic-scale-physics.de/lattice/struk/b2.html B2] cubic) is thermodynamically favored at higher temperatures. Since these structures have different lattice sizes and symmetry, cooling austenite into martensite introduces internal strain energy in the martensitic phase. To reduce this energy, the martensitic phase forms many twins—this is called "self-accommodating twinning" and is the twinning version of geometrically necessary dislocations. Since the shape memory alloy will be manufactured from a higher temperature and is usually engineered so that the martensitic phase is dominant at operating temperature to take advantage of the shape memory effect, SMAs "start" highly twinned.
When the martensite is loaded, these self-accommodating twins provide an easy path for deformation. Applied stresses will detwin the martensite, but all of the atoms stay in the same position relative to the nearby atoms—no atomic bonds are broken or reformed (as they would be by dislocation motion). Thus, when the temperature is raised and austenite becomes thermodynamically favored, all of the atoms rearrange to the B2 structure which happens to be the same macroscopic shape as the B19' pre-deformation shape. This phase transformation happens extremely quickly and gives SMAs their distinctive "snap".
Repeated use of the shape-memory effect may lead to a shift of the characteristic transformation temperatures (this effect is known as functional fatigue, as it is closely related with a change of microstructural and functional properties of the material). The maximum temperature at which SMAs can no longer be stress induced is called M, where the SMAs are permanently deformed.