Statistical mechanics of immunity from genes to populations