I fear that the whales are desperate to save their kind from extinction. Habitat destruction (food supply shortage) is an existential threat to whales. They need a lot of food, and their food supply is being disrupted. Being the intelligent and possibly very caring animals they are, they are sacrificing themselves so that some of their kind can live. Instead of just not eating and leaving the food for others they beach themselves so they can die quickly instead of slowly dying. They know there is not enough food for all of them so some of them commit suicide to save the others.