Nat is to put it politely a cross layer process, or to put it less politely a blatant layering violation.
There is a saying about models, "all models are wrong, some models are useful". Models are a useful tool to break down problems and aid understanding, but you should not expect reality to perfectly conform to your model.
On the subjet of OSI, networking vendors like to use the OSI layer numbers, but it's important to realise that the real world networking protocols we use today were not generally designed to conform to the OSI model.
It's also important to realise that networking standards mostly concern themselves with stuff that can be seen on the wire. What exactly happens inside a computer or middlebox is mostly the concern of an individual implementer.
The IPv4 header contains a "protocol" field which carries the protocol number of the transport protocol in use. This is intended for use by the end host receiving the packet, but a NAT (or L4 aware firewall) will also use it to identify the transport protocol that is in use.
For the most common transport protocols, TCP, UDP and ICMP the NAT will certainly have protocol-specific implementations for extraction and translation of packet data. For TCP and UDP it will know how to extract/modify the port numbers and how to recalculate the checksums to take account of the new IP addresses and ports.
ICMP traffic that can be handled by NATs is generally divided into two categories. Query/Response and Errors. Query/response messages can be handled in a similar way to TCP and UDP packets, treating the Type/Code and Identifier fields in a similar way to port numbers. Error messages are handled by extracting internal headers of the "context" packet and translating them.
It's worth noting that while the NAT has to be aware of some transport layer fields, the NAT process does not have to fully implement the transport protocol. It is very likely that the implementation of NAT and firewalling for a particular protocol will be separate from the regular implementation of that protocol and a middlebox may have NAT and firewalling support for protocols that it does not have support for acting as an end host for.