Humans and other animals have lots of innate behaviors that are not learned from observation, i.e. behaviors that are hard-wired into our nervous system, and this is one of them. Suckling reflexes in mammals and the Moro reflex is human babies (which we grow out of) are other simple examples.
The stretching behaviours you are referring to are usually labelled pandiculation in humans (defined as involuntary stretching of the soft tissues), and yawning is often considered a special case of this. These kinds of behaviours are also normally related to transition periods between high-low activity in animals (Walusinskie, 2006). In practice, stretching functions as a way to reverse the muscular atonia during REM sleep, and is in this sense a way to restore homeostatic functions (Fraser, 1989; Walusinskie, 2006).
A paper by Rial et al (2010) deals with the evolution of sleep and wakefulness in mammals from our reptile predecessors, and indicates that stretching behaviours might have originated/evolved from post-basking activities, more specifically risk-assessment behaviours, such as:
...risk assessment behaviour (RAB) and consists of the suspension of current behaviour, to be replaced by head dipping movements, eye scanning, rearing and
adopting stretch attending postures...
There is most likely much more to be said about this, and the paper cited above contains many references that can provide further clarification and evidence. A short comparative discussion of pandiculation is found in Frasier (1989).