One rather famous example is of a BUD/S (usually called SEAL) selectee who drowned himself. When pulled out of the pool and resuscitated, he apologized and thought he failed out of the selection process. The instructor replied something like "heck no, you passed. We can always teach you how to swim. No one can teach you to never give up".
https://en.wikipedia.org/wiki/United_States_Navy_SEAL_select...
I'm simplifying things quite a bit, but almost all military contracts are 8-year (typically split into a 4-year active and 4-year reserve period). If you leave on your own volition during this period, you typically have to repay the cost to the government to train you. And any contract that you're on where you received a signing bonus you have to pay back.
The actual mechanism for doing this is a different between officers and enlisted and they're some paperwork but functionally you can leave if you're really motivated to and for the most part people won't stop you (outside of a few conversations where people advise you against it).
The type of discharge you receive depends on the circumstances but generally there's a way to still get an honorable discharge (hardship, education, family, conscientious objector).
There's also the more practical quitting special forces vs leaving the military entirely. Tier 1 units only want people who want to be there and if you don't you can get transferred to some other job in the military in like a day if you really wanted to.