There's the question of HOW homosexuality happens, versus WHY it happens. I think the OP wants to know the latter.
Since I'm not a scientist, I have to rely upon a more philosophical approach. The first thing I observe is that gays have existed throughout recorded history, and at what appears to be a fairly constant rate. That would argue against homosexuality being a random deviation that shows up like a life-threatening birth defect. It's persistence instead argues for it having a benefit.
But that would appear to conflict with a Darwinian view of evolution, since a creature that does not reproduce cannot pass on any traits, gay ones or otherwise. Indeed, pure Darwinism has reproduction as the fundamental benefit, all other inherited traits being secondary to that one purpose of survival of the species.
But in that phrase, which seems to confound us, may indeed lie the answer: survival of the SPECIES, not the individual. Gays do not benefit themselves, but rather, greater humanity, by providing special skills and labor. And that is why humanity keeps producing them, when they cannot (or will not) reproduce themselves.
If humans lived solely in isolated family breeding units the issue of homosexuality might not arise. Indeed, it could indeed be seen as a detriment. And I notice that this image is at the core of anti-gay attitudes: family values, preserving the family unit, always family, family, family.
Except, that isn't how humans actually live. We are social creatures, whose culture and civilization depends upon a highly complex interaction among its members. Despite the romantic and unrealistic view of the "rugged individualist" we in fact could not live in a modern world entirely on our own.
And part of that life includes artistic and other creative endeavors. Tasks which gays can take because our lives aren't consumed with child rearing. Yet, at the same time, we can assist with child rearing as needed. I therefore see homosexuality much like other divisions of labor within society.
Now you may say, yeah, but humans don't need a painting to survive as a species. I wouldn't be so sure. Painting and other uniquely human expressions may have been essential to our intellectual evolution, that made us as smart and successful as we are. We may crave certain intellectual pursuits as much as we crave food. And who says our evolution has reached its end? Some studies suggest we continue to evolve today.
So that we gays are part of the entire fabric of human life, one of the many forces that drives & motivates us, even if we fail to see it ourselves. A world without gays might see the devolution of humanity, and we'd return to being the primitive apes we once were.