The same way the Dothraki did, presumably they either fled to the surrounding areas, carried on fighting up where they were "wiped out" or fled back to Winterfell. We do see some come back to Winterfell after all. Whilst David Benioff says the following in the Inside the Episode it is contradicted later on in the season.
David: What they see is just the end of the Dothraki, essentially.
Game of Thrones, Season 8 Episode 3, "Inside the Episode"
However, later on we see that only around half of the Dothraki were actually killed.
Grey Worm: Half are gone. Grey Worm removes half of the Unsullied markers.
Jon Snow: The Northmen as well. Jon Snow removes half of the Northmen markers.
Yohn Royce removes half of the Arryn markers.
Dothraki soldier removes half of the Dothraki markers.
[...]
Tyrion Lannister: So if all are in agreement Jon and Ser Davos will ride down the Kingsroad with the Northern troops and the bulk of the remaining Dothraki and Unsullied. A smaller group of us will ride to White Harbor, and sail from there to Dragonstone with our queen and her dragons accompanying us from above.
Game of Thrones, Season 8 Episode 4, "The Last of the Starks"
It's not actually explained where they all were and what happened to them as far as I know but I think the above guesses are somewhat accurate. Lastly, Ghost has been known to wander and do his own thing, it's possible after losing his ear and being injured he just left and came back later on.