noeagles:

however, there are circumstances where the numbers of samples must be the same or pre-determined. So, I wonder how to impleme


If I understand you correctly, you need to use a sampler but keep the data balance. If your data is large enough, then even after random sampling it will be (almost) balanced.
If not, the easiest way would be to generate a weight vector denoting your data balance, then to pass this vector to the loss function.
See for example,
class CrossEntropyLoss(_WeightedLoss) 
...
Args:
        weight (Tensor, optional): a manual rescaling weight given to each class.
            If given, has to be a Tensor of size `C`

in:
https://pytorch.org/docs/stable/_modules/torch/nn/modules/loss.html 4