This is something I always found to be a bit of a contradiction.
The Torah states that a person's sins are their own to bear and that no one may die for the sins of another.
Parents shall not be put to death for children, nor children be put to death for parents: a person shall be put to death only for his own crime. - Devarim 24:16
At the same time, we see examples where the Torah cites Hahsem is punishing either entire nations of people or multiple generations of people for a previous wrongdoing.
- The killing of the Egyptian children for the sins of their parents.
- The killing of the Canaanites (including children)
- The killing of the Amalekites (including children)
Cursing multiple generations of those who worship graven images and false gods:
You shall not bow down to them or serve them. For I the LORD your God am an impassioned God, visiting the guilt of the parents upon the children, upon the third and upon the fourth generations of those who reject Me, - Shemot 20:5
Psalms even speaks of it being a blessing to inflict punishments against others in the way they inflicted them upon us.
Fair Babylon, you predator, a blessing on him who repays you in kind what you have inflicted on us; a blessing on him who seizes your babies and dashes them against the rocks! - Tehillim 137:8-9
How exactly do we rationalize this with regards to the idea that sins fall upon the individual alone and not their entire community/family/nation?