It doesn't "know" where it is. It instead estimates where it is, with the quality of the estimation degrading with time. It is using a 21st century equivalent of the "dead reckoning" techniques that enabled the Age Of Sail. (In other words, it's using a Kalman filter that lacks position and attitude updates.)
From How NASA Designed a Helicopter That Could Fly Autonomously on Mars,
Can you describe what sensors Ingenuity uses for navigation?
We use a cellphone-grade IMU, a laser altimeter (from SparkFun), and a downward-pointing VGA camera for monocular feature tracking. A few dozen features are compared frame to frame to track relative position to figure out direction and speed, which is how the helicopter navigates. It’s all done by estimates of position, as opposed to memorizing features or creating a map.
We also have an inclinometer that we use to establish the tilt of the ground just during takeoff, and we have a cellphone-grade 13 megapixel color camera that isn’t used for navigation, but we’re going to try to take some nice pictures while we’re flying.
Altogether, this does not have the makings of a particularly sophisticated autonomous helicopter with regard to navigation. There are Earth-based autonomous helicopters and drone aircraft that are far more sophisticated in this regard. Ingenuity doesn't need to be all that sophisticated with regard to navigation. Ingenuity is a technology demonstration article. The principal goal is to demonstrate that a helicopter on Mars is feasible. Ingenuity will make short flights over terrain specifically chosen to be more or less flat (except for pebbles that can be used for the optical flow algorithm).
This is not meant to disparage Ingenuity. The bulk of the development efforts went into the helicopter itself, and on a slim budget. The navigation had to be "good enough" to enable the demonstration of the technology. The next iteration (and since the first flight succeeded, there most likely be a next iteration) will have a more sophisticated navigation system.