Typically you have to carve it. In Germany I once visited a custom furniture maker who specialized in making plush oversized padded furniture. They had several tools for carving foam from blocks. One of those tools was a machine like a bandsaw which worked with a very thin wire. Using that they could slice through the foam and cut it into shapes.
If you are wanting to make form fitted cavities then it's going to be difficult using the flat foam you can get at the fabric store. My advice would be to try to cut layers of different sizes and stack them.
You can also use your razor to cut tapered cavities which will also work. I have seen someone use an electric bread knife to cut foam and it worked well (reminds me that I need to go get one).
Basically you can cut straight cavities as well that are the size of about the middle point of your piece and the foam will fit around the piece. As long as you have enough resistance on the sides of the cavities but also enough room to allow the piece to be put in without too much force you should be good to go.