This is a ridiculously complicated topic, but the short story is that hospitals that employ residents are paid a lump sum by CMS for each resident that they employ. Much of this goes to support the resident's salary, but significant portions also go to the hospital to support "direct medical education" and "indirect medical education." As an example, at my institution the average resident's salary is somewhere around $60-65k, but the hospital receives a total of about $90k per resident. The remaining amount goes to the hospital to support a variety of things related to having residents at their institution. The exact formulae used to calculate how much CMS will pay and where the residents can actually work in order to be supported by that funding are complex and not straightforward.
As mentioned above, this is the primary but not only source of residency funding. In my state, for example, millions of dollars are paid to medical institutions to also fund residency slots. Compared to the funding provided by CMS, this is a comparatively small amount but nevertheless is present.
As far as I know, there is no requirement that hospitals receive money to fund residency slots. They could simply fund residency slots themselves, if they wanted to. However, the bureaucratic requirements dictated by the ACGME in order to have an accredited program are so onerous that this is likely a financially silly move to make, even with an army of relatively low-paid physicians bolstering the institution's workforce. Programs must have dedicated staff to support the program in order to be accredited, and physicians that serve as program directors, assistant program directors, etc. must, by ACGME mandate, set aside a certain amount of their time to their PD/APD role. In a situation where a hospital is funding their own residencies, this is a direct loss to income generated from clinical services as that is time that the physician cannot be doing clinical work and is, instead, doing nothing that is financially productive for the institution. This doesn't even take into account the time required to actually fulfill the educational aspects of residency training, which requires even more physician time.
Since hospitals generally are not interested in pissing money down the drain, they fund residency slots based on their ability to find revenue streams to support them. At my institution, for example, requests to expand programs must be approved by the GME office, and one of the criteria for approving an expansion is that the department must be able to demonstrate that they have a stable source of funding for the position(s). These streams come almost entirely from government.