I do not check my code, hope it could help you…
# generate input data 
batch_size, seq, embedding, indices_len = 30, 20, 5, 3
x = torch.randn((batch_size, seq, embedding))
indices = torch.randint(0, seq - 1, (batch_size, indices_len, 2)).sort(dim=-1)[0]
indices[:, :, 1] += 1 

# Now Let's go to calculate the result 
# Step 1. Note that x[start:end] equals to cumsum[end] - cumsum[start]. 
# Unfortunately, I donot know how to scatter a 2D tensor. Let me reshape it.
cumsum_x = torch.cumsum(x, dim=1)
cumsum_x = .view(-1, embedding)  # (30x20, 5)

# Step 2. Flatten indices.
lower_index = (indices[..., 0] + torch.arange(batch_size)[:, None] * seq).view(-1)
higher_index = (indices[..., 1] + torch.arange(batch_size)[:, None] * seq).view(-1)

# Step 3, select elements
lower = cumsum_x[lower_index, :].view(batch_size, indices_len, embedding)
higher = cumsum_x[higher_index, :].view(batch_size, indices_len, embedding)

# Step 4, mean
step = indices[..., 1:2] - indices[..., 0:1]
result = (higher - lower) / step.float()