If you don’t know the targets beforehand, you would need to iterate all samples once and count all class occurrences. Once this is calculated, you could use the sklearn.utils.class_weight.compute_class_weight or just these two lines of code:
class_sample_count = np.unique(target, return_counts=True)[1]
weight = 1. / class_sample_count
samples_weight = weight[target]
samples_weight = torch.from_numpy(samples_weight)