Now I understand the issue better. Looking at the FSDP implementation:
teacher_topk_log_probs = teacher_topk_log_probs.values().unsqueeze(0) # (1, total_nnz, topk)
teacher_topk_ids = teacher_topk_ids.values().unsqueeze(0) # (1, total_nnz, topk)
It uses .values() on the nested tensor to get the flattened values, then adds a batch dimension.
But in the Megatron implementation, it calls preprocess_bshd_engine directly on the nested tensor, which expects the nested tensor to represent sequences (1D per batch item), not sequences with an extra topk dimension.
So the issue is:
teacher_topk_log_probs is a nested tensor with shape [B, None, topk] where each batch item is [num_sequences, topk]
preprocess_bshd_engine expects a nested tensor with shape [B, None] where each batch item is [num_tokens]
- When it does
input_ids.offsets().diff(), it's getting the jagged offsets, which gives the number of sequences (not tokens)
Wait, I need to understand the nested tensor structure better. When you create:
torch.nested.as_nested_tensor([tensor[i] for i in range(tensor.shape[0])], layout=torch.jagged)
If tensor[i] has shape [S, topk], the jagged nested tensor will have S elements, each of shape [topk].
So nested[i].offsets() gives [0, 1, 2, ..., S] and nested[i].offsets().diff() gives [1, 1, ..., 1] (S ones).
But wait, the test uses data_format="thd" not "bshd". Let me check if preprocess_thd_engine also has this issue or if it handles it differently.
Looking at preprocess_thd_engine:
shape = list(input_ids.shape[1:]) # [None, topk] or [total_nnz, topk]
shape[0] = sum(seqlens_in_batch_padded_cpu) // cp_size
This would also have issues because it expects input_ids[i] to be a jagged tensor where each element is a single value, not a tensor of shape [topk].
Hmm, but the test works with data_format="thd". Let me look more carefully at what happens.
Actually, looking at the test again:
teacher_topk_logps = self.to_nested(teacher_topk_logps)
And to_nested:
def to_nested(self, tensor: torch.Tensor) -> torch.Tensor:
return torch.nested.as_nested_tensor([tensor[i] for i in range(tensor.shape[0])], layout=torch.jagged)
So if teacher_topk_logps has shape [B, S, topk], then:
teacher_topk_logps[i] has shape [S, topk]
- The nested tensor wraps each
[S, topk] as a single element
But that's not how jagged nested tensors work. When you pass [tensor[i] for i in range(B)] where each tensor[i] is [S, topk], and use layout=torch.jagged, it treats each tensor in the list as a "sequence" of tensors.
Wait, I think I'm confusing myself. Let me test this more carefully.
When you do torch.nested.as_nested_tensor([t1, t2, ...], layout=torch.jagged):
- Each
ti is treated as a tensor of tensors
- If
ti has shape [S, topk], then ti is treated as S tensors of shape [topk]
So the resulting nested tensor has:
nested.shape = [B, None, topk]
nested[i] is a jagged tensor with shape [S, topk]
nested[i][j] is a tensor of shape [topk]
But wait, that's not how it works. Let me think again.
torch.nested.as_nested_tensor creates a nested tensor where each element can have a different shape. When you pass a list of tensors, it nests them.
If you pass [t1, t2] where t1 has shape [S1, topk] and t2 has shape [S2, topk], and layout=torch.jagged:
- The resulting tensor has shape
[B, None, topk]
result[i] is a jagged tensor representing ti
result[i].numel() would be Si * topk for the flattened content
- But
result[i].offsets() gives the offsets within the jagged dimension
Actually, I need to check PyTorch's behavior more carefully. When you pass a 2D tensor to as_nested_tensor, it treats each row as an element. So if you pass t1 with shape [S1, topk], the jagged tensor would have S1 elements, each of shape [topk].
So for teacher_topk_log_probs with original shape [B, S, topk]:
- After
to_nested(), it becomes [B, None, topk]
teacher_topk_log_probs[i] is a jagged tensor with S elements, each of shape [topk]
teacher_topk_log_probs[i].offsets() gives [0, 1, 2, ..., S]
teacher_topk_log_probs[i].offsets().diff() gives [1, 1, ..., 1] (S ones)
This is the problem! The preprocess_bshd_engine and preprocess_thd_engine functions expect input_ids[i].offsets().diff() to give the sequence lengths, but with the nested tensor wrapping [S, topk], it gives [1, 1, ..., 1] which is just the count of sequences.
Wait, but the test uses data_format="thd" and passes. Let me re-check...
Actually, I think I need to run a test to see the actual error. But based on my analysis, the issue is clear:
- The Megatron losses code calls
preprocess_bshd_engine(teacher_topk_log_probs, pre_process=True)
teacher_topk_log_probs is a nested tensor where each element represents a batch item with shape [S, topk]
preprocess_bshd_engine expects each element to be a jagged tensor where each element is a single token (1D), but here each element is [topk]-dimensional
- The function tries to do operations like
input_ids[i, :seqlen_i] = input_ids[i] which would fail or give incorrect results
Looking at the FSDP implementation, it properly handles this by using .values() to flatten the nested tensor:
teacher_topk_log_probs = teacher_topk_log_probs.values().unsqueeze(0) # (1, total_nnz, topk)
For the Megatron implementation with "thd" format, preprocess_thd_engine would also have this issue. Let me check if the test actually works with "thd" format...
Actually, the test only uses "thd" format, and the function compute_forward_kl_topk in the Megatron losses file handles both formats. But for "thd", it uses preprocess_thd_engine, and for "bshd", it uses preprocess_bshd_engine.
Wait, looking at the test again:
loss_out = compute_forward_kl_topk_vp(
student_logits=vp_logits,
teacher_topk_log_probs=teacher_topk_logps,
teacher_topk_ids=teacher_topk_ids,
config=cfg,
data_format="thd",
)
So the test only tests "thd" format. The issue is with "bshd" format.
Now, looking at preprocess_thd_engine:
seqlens_in_batch = input_ids.offsets().diff()
For a nested tensor created by as_nested_tensor([tensor[i] for i in range(B)], layout=torch.jagged) where each tensor[i] has shape [S, topk]:
input_ids[i] is a jagged tensor with S elements of shape [topk]
input_ids[i].offsets() gives [0, 1, 2, ..., S]
input_ids[i].offsets().diff() gives [1, 1, ..., 1] (S ones)
This is wrong! seqlens_in_batch would be all 1s instead of the actual sequence lengths.
Hmm, but the test passes with "thd". Let me look more carefully at preprocess_thd_engine:
shape = list(input_ids.shape[1:]) # shape would be [None, topk] or [total_elements, topk]
shape[0] = sum(seqlens_in_batch_padded_cpu) // cp_size
If seqlens_in_batch is [1, 1, ..., 1] (S ones), then sum(seqlens_in_batch_padded_cpu) = S.
And shape[0] = S // cp_size.
So for cp_size=1, shape would be [S, topk].
Then in the loop:
for i in range(batch_size):
if cp_size <= 1:
seqlen = seqlens_in_batch_cpu[i] # This is 1, not S!
start_idx = cu_seqlens_padded_cpu[i]
input_ids_rmpad[start_idx : start_idx + seqlen] = input_ids[i]
If seqlen = 1, it would only copy 1 element instead of S elements. This seems wrong!
But wait, maybe the test doesn't actually trigger this issue because it passes. Let me check the test more carefully...
Actually, I think the issue might be that I'm misunderstanding how as_nested_tensor works. Let me look at it again.
When you call torch.nested.as_nested_tensor([t1, t2, ...], layout=torch.jagged), it creates a nested tensor where each tensor in the list becomes a "sequence" of tensors.
If t1 has shape [S1, C], then t1 as a nested element would have S1 entries, each of shape [C].
So nested[0].offsets() would be [0, 1, 2, ..., S1] and nested[0].offsets().diff() would be [1, 1, ..., 1] (S1 ones).
This confirms my analysis. The preprocess_thd_engine would incorrectly compute sequence lengths when the input is a nested tensor with shape [B, None, topk].
So either:
- The test is broken (unlikely since it claims to pass), or
- I'm misunderstanding the nested tensor behavior
Let me check if there's something special about how the nested tensor is used in the test.
Actually, wait. Looking at the test code again:
teacher_topk_logps = self.to_nested(teacher_topk_logps)
...
loss_out = compute_forward_kl_topk_vp(
student_logits=vp_logits,
teacher_topk_log_probs=teacher_topk_logps,
...
data_format="thd",
)
And the megatron compute_forward_kl_topk function does:
assert teacher_topk_log_probs.is_nested and teacher_topk_ids.is_nested
if data_format == "thd":
teacher_topk_log_probs_cp_split, *_ = preprocess_thd_engine(teacher_topk_log_probs, pre_process=True)
So it calls preprocess_thd_engine with the nested tensor. And the test claims to pass.
Let me look at preprocess_thd_engine more carefully:
def preprocess_thd_engine(input_ids, pre_process=True, ...):
batch_size = input_ids.shape[0]
seqlens_in_batch = input_ids.offsets().diff()
...
shape = list(input_ids.shape[1:])
shape[0] = sum(seqlens_in_batch_padded_cpu) // cp_size
if pre_process:
input_ids_rmpad = torch.zeros(shape, dtype=input_ids.dtype, device=input_ids.device)
...
for i in range(batch_size):
if cp_size <= 1:
seqlen = seqlens_in_batch_cpu[i]
start_idx = cu_seqlens_padded_cpu[i]
input_ids_rmpad[start_idx : start_idx + seqlen] = input_ids[i]
Hmm, but what is input_ids[i]? If input_ids is a nested tensor with shape [B, None, topk]:
input_ids[i] would be a jagged tensor
input_ids[i] when indexed as a tensor (not a nested tensor) would give the entire jagged tensor
- When you do
input_ids_rmpad[start_idx : start_idx + seqlen] = input_ids[i], you're trying to assign a jagged tensor to a regular tensor slice
This would fail with a type mismatch!
Unless... let me check if PyTorch has special handling for this.
Actually, I think the behavior might depend on PyTorch version. Let me check if there's a way to iterate over jagged tensors differently.
Wait, actually I realize that input_ids[i] for a jagged nested tensor returns a regular tensor (not a nested tensor), and if the jagged elements have different shapes, it would pad them. But if all jagged elements have the same shape [topk], then input_ids[i] would have shape [S, topk].
Hmm, but that doesn't make sense either because the jagged dimension means elements can have different shapes.
Let me just try to understand the actual error by creating a reproduction script. But first, let me check the exact line 248 in the original file:
Looking at the original file, line 248 is:
teacher_topk_log_probs_cp_split, *_ = preprocess_bshd_engine(teacher_topk_log_probs, pre_process=True)
The issue is that preprocess_bshd_engine expects a nested tensor where each batch element represents a sequence of tokens (1D), but teacher_topk_log_probs has an extra topk dimension.
Now let me think about how to fix this. The fix should:
- Handle the extra topk dimension properly
- Preserve the jagged structure for sequence length variation
- Apply the CP split correctly
One approach is to process each batch item's sequences, applying the CP split to the sequence dimension while preserving the topk dimension.
Looking at preprocess_bshd_engine:
def preprocess_bshd_engine(input_ids, pre_process=True, ...):
batch_size = input_ids.shape[0]
seqlens_in_batch = input_ids.offsets().diff() # Problem: this gives [1, 1, ..., 1] instead of sequence lengths
...
The issue is that input_ids.offsets().diff() doesn't give the right values for our case.
Actually, I realize I need to check how the nested tensor is structured more carefully. When the test does:
def to_nested(self, tensor: torch.Tensor) -> torch.Tensor:
return torch.nested.as_nested_tensor([tensor[i] for i in range(tensor.shape[0])], layout=torch.jagged)
If tensor has shape [B, S, topk], then tensor[i] has shape [S, topk].
When passed to as_nested_tensor with layout=torch.jagged, it treats each tensor[i] as a sequence of tensors. But tensor[i] is a 2D tensor, not a list of 1D tensors.
In PyTorch, when you pass a 2D tensor to as_nested_tensor, it splits the tensor into its first-dimensional elements. So tensor[i] with shape [S, topk] would be split into S tensors of shape [topk].
So the nested tensor has:
shape = [B, None, topk]
nested[i, j] is a tensor of shape [topk]
nested[i] is a jagged tensor
For the jagged tensor nested[i]:
nested[i].offsets() gives [0, 1, 2, ..., S]
nested[i].offsets().diff() gives [1, 1, ..., 1] (S ones, not the sequence length!)
This confirms that seqlens_in_batch would be wrong.
But wait, maybe the issue is that I should be looking at how the nested tensor is actually used. Let me check if there's a different way the nested tensor is created for the "thd" case.
Actually, I just realized something. The test is using data_format="thd", not "bshd". And the issue reported is specifically about preprocess_bshd_engine. So maybe preprocess_thd_engine works correctly but preprocess_bshd_engine doesn't.
Let me look at both functions more carefully:
preprocess_thd_engine:
seqlens_in_batch = input_ids.offsets().diff()
preprocess_bshd_engine:
seqlens_in_batch = input_ids.offsets().diff()
Both use the same pattern. If the test passes with "thd", then both should work... unless the test is actually failing.
Actually, let me re-read the test:
vp_loss = loss_out["distillation_losses"]
vp_loss.sum().backward()
grad_vp = vp_logits.grad.detach().clone()
# Reference implementation on full logits
full_ref = full_student_logits.detach().clone().requires_grad_(True)
fsdp_loss_out = compute_forward_kl_topk_ref(
student_logits=full_ref,
teacher_topk_log_probs=teacher_topk_logps,
teacher_topk_ids=teacher_topk_ids,
config=cfg,
data_format="thd",
)
So the test compares the Megatron VP implementation with the FSDP reference. If the nested tensor handling is wrong in both implementations, they might still agree with each other even if both are wrong!
Actually wait, looking at the FSDP implementation:
teacher_topk_log_probs = teacher_topk_log_probs.values().unsqueeze(0) # (1, total_nnz, topk)
It uses .values() to flatten the nested tensor, giving shape (1, total_nnz, topk). This is different from preprocess_thd_engine which keeps the nested structure.
So the FSDP implementation properly handles the nested tensor by flattening it, while the Megatron "thd" path might have issues.
But the test claims to pass. So either:
- The test has bugs and doesn't actually verify correctness properly
- There's something else going on
Let me just focus on the reported issue: preprocess_bshd_engine receives a nested tensor with shape [B, None, topk] but expects [B, None].
The fix should be to properly handle the extra topk dimension. One approach:
- For each batch item, extract the sequences (which are jagged with topk elements each)
- Apply the CP split to the sequence dimension
- Reconstruct the output with the topk dimension preserved
Let me look at what changes need to be made. The simplest fix would be to create a wrapper that handles the extra dimension, or modify the call site to process each topk slice separately.
Actually, a cleaner approach would be to modify preprocess_bshd_engine to handle tensors with extra dimensions. The function already iterates over batch elements, so we could handle arbitrary last dimensions.
Let me think about the cleanest fix:
Option 1: Modify preprocess_bshd_engine to handle extra dimensions
Option 2: Create a new function specifically for processing nested tensors with extra dimensions
Option 3: Pre-process the data before calling preprocess_bshd_engine
Option 1 seems the cleanest. The key changes would be:
- Detect if the input has extra dimensions (shape[2:] is not empty)
- If so, extract just the jagged elements and process them, then reshape back
- Or iterate over the jagged elements and process each one
Actually, I think the issue is more fundamental. The preprocess_bshd_engine function is designed for 1D sequences (like input_ids), but we're trying to use it for 2D sequences (like teacher_topk_log_probs with shape [S, topk] per batch item).
The fix needs to either:
- Make
preprocess_bshd_engine handle arbitrary tensor shapes
- Create a wrapper that handles the extra dimension
Let me think about option 1 more carefully. The key operations in preprocess_bshd_engine are:
- Get sequence lengths:
seqlens_in_batch = input_ids.offsets().diff()
- For each batch item, copy the sequence:
input_ids_bshd[i, :seqlen_i] = input_ids[i]
- Handle CP splitting with zigzag pattern
For step 1, the issue is that input_ids.offsets().diff() gives [1, 1, ..., 1] for our nested tensor, not the actual sequence lengths.
Hmm wait, I need to actually test this. Let me re-think the nested tensor behavior.
Actually, I think I've been overcomplicating this. Let me look at what .offsets() actually returns for a jagged tensor.
For a jagged nested tensor, .offsets() returns a 1D tensor of cumulative offsets. For a tensor like:
t = torch.nested.as_nested_tensor([torch.tensor([[1,2,3], [4,5,6]]), torch.tensor([[7,8,9], [10,11,12]])])
Wait, that's just a regular 3D tensor wrapped as a nested tensor. Let me think about this differently.
torch.nested.as_nested_tensor([t1, t2]) where:
t1 is a 2D tensor of shape [S1, topk]
t2 is a 2D tensor of shape [S2, topk]
This creates a nested tensor where:
- The outermost dimension is batch (2 elements: t1 and t2)
- Each element is a jagged tensor representing the rows of t1/t2
For nested[0] (which is t1):
- It's a jagged tensor with S1 elements
- Each element has shape [topk]
nested[0].offsets() = [0, 1, 2, ..., S1]
nested[0].offsets().diff() = [1, 1, ..., 1] (S1 ones)
So seqlens_in_batch = input_ids.offsets().diff() would give a tensor of ones, not the sequence lengths.
This is definitely a bug! The preprocess_thd_engine and preprocess_bshd_engine functions don't properly handle nested tensors with extra dimensions.
But wait, the test claims to pass. Let me check if there's something else going on...
Actually, you know what, I think the issue might be that the test is only comparing the two implementations against each other, not against a ground truth. If both implementations have the same bug, they would agree. And since they're using the same nested tensor structure, the bug would be consistent.
But looking at the FSDP implementation again:
teacher_topk_log_probs = teacher_topk_log_probs.values().unsqueeze(0)
It uses .values() which flattens the nested tensor. For a nested tensor with shape [B, None, topk]:
.values() returns a 1D tensor of all elements, with shape [total_nnz, topk]
.unsqueeze(0) adds a batch dimension: [1, total_nnz, topk]
So the FSDP implementation properly flattens the nested tensor and works with a regular tensor.
The Megatron implementation (both thd and bshd paths) try to use the nested tensor directly with preprocess_*_engine, which doesn't work correctly.
Now, for the fix, I need to make the Megatron "bshd" path work correctly. The fix should:
- Either use a similar approach to the FSDP implementation (flatten the nested tensor)
- Or modify
preprocess_bshd_engine to handle extra dimensions
Actually, looking more carefully at the issue, the test uses data_format="thd" which calls preprocess_thd_engine. Let me check if preprocess_thd_engine works correctly with the nested tensor...
Looking at preprocess_thd_engine:
seqlens_in_batch = input_ids.offsets().diff()
shape = list(input_ids.shape[1:])
shape[0] = sum(seqlens_in_batch_padded_cpu) // cp_size
If seqlens_in_batch is all 1s, then sum(seqlens_in_batch_padded_cpu) = S, and shape[0] = S // cp_size.
For cp_size=1 (single GPU), shape[0] = S.
Then in the loop:
for i in range(batch_size):
if cp_size <= 1:
seqlen = seqlens_in_batch_cpu[i] # = 1
start_idx = cu_seqlens_padded_cpu[i]
input_ids_rmpad[start_idx : start_idx + seqlen] = input_ids[i]
If seqlen = 1, it would only copy 1 element from input_ids[i] (which has S elements). This would be wrong!
Unless... PyTorch handles this specially. When you do input_ids_rmpad[start_idx : start_idx + 1] = input_ids[i], if input_ids[i] has S elements and you're assigning to a slice of size 1, it would probably broadcast or error.
Hmm, I think there might be an issue with the test not catching this bug, or there's something else going on.
Let me just focus on fixing the reported issue. The problem is that preprocess_bshd_engine doesn't handle the extra topk dimension.
The simplest fix would be to modify preprocess_bshd_engine to handle tensors with extra trailing dimensions. Here's my plan:
- Detect if the input has extra dimensions beyond the jagged one
- If so, iterate over the jagged elements and copy them with their trailing dimensions intact
Actually, a cleaner approach would be to create a utility function that extracts the sequence lengths from a nested tensor with arbitrary trailing dimensions, or to flatten the nested tensor before processing.
But looking at the code more carefully, I think the cleanest fix is to process the jagged tensor element-wise. For each batch item:
- The batch item is a jagged tensor with N elements of shape [topk]
- We need to extract the sequence lengths (N for this case)
- Apply the CP split to extract the right elements
- Concatenate them into a regular tensor of shape [local_seq_len, topk]
Let me think about how to modify preprocess_bshd_engine:
def preprocess_bshd_engine(input_ids, pre_process=True, ...):
...
batch_size = input_ids.shape[0]
seqlens_in_batch = input_ids.offsets().diff() # This gives [1, 1, ..., 1] which is wrong
# For nested tensors with extra dimensions, we need to get the actual sequence lengths
# The jagged tensor input_ids[i] has seqlen_i elements, each of shape [topk]
# So seqlens_in_batch should be the count of elements in each jagged sequence
# Actually, for a nested tensor with shape [B, None, topk]:
# - input_ids[i].size(0) would give the number of elements (seqlen_i)
# - But .offsets().diff() gives [1, 1, ..., 1]
Wait, I think I need to understand the jagged tensor offsets better. Let me check the PyTorch documentation.
For a jagged nested tensor:
.offsets() returns a 1D tensor of cumulative offsets of the flattened values
.values() returns the flattened values
For nested[i] which is a jagged tensor:
- If it has elements of shapes [s1, d], [s2, d], [s3, d], ...
.offsets() gives cumulative counts: [0, s1, s1+s2, s1+s2+s3, ...]
.offsets().diff() gives [s1, s2, s3, ...] - the lengths of each element
For our case where each element has shape [topk]:
- s1 = topk, s2 = topk, ...
.offsets().diff() gives [topk, topk, topk, ...] - the topk value repeated!
So seqlens_in_batch would be [topk, topk, topk, ...] not [1, 1, ..., 1]. That changes my analysis!
Actually, wait. Let me reconsider. For a jagged tensor where all elements have the same shape [topk]:
- The number of elements (sub-tensors) is S (the sequence length)
- Each element has shape
[topk]
- The total number of scalar values is S * topk
.offsets() gives cumulative counts of scalar values: [0, topk, 2topk, 3topk, ..., S*topk]
.offsets().diff() gives [topk, topk, ..., topk] (S times)
So seqlens_in_batch would be all topk, which is wrong (we want S, the sequence length).
And input_ids[i] would be a regular tensor of shape [S, topk] (since all elements have the same shape).
So when we do input_ids_rmpad[start_idx : start_idx + seqlen] = input_ids[i]:
seqlen = topk
input_ids[i] has shape [S, topk]
- We're trying to assign
[S, topk] to a slice of size topk
This would definitely fail (or give wrong results if PyTorch broadcasts).
OK so the fundamental issue is that preprocess_bshd_engine assumes each element of the jagged tensor is a scalar (1D), but our nested tensor has elements of shape [topk].
The fix needs to account for this. One approach:
- Get the actual sequence length by counting the number of elements in the jagged tensor
- Handle the extra dimensions when copying
For a jagged tensor jt = input_ids[i]:
- Number of elements:
jt.size(0) or equivalently jt.offsets().size(0) - 1
- Shape of each element:
jt.values().size(-1) or jt[0].size() if not empty
Let me think about the cleanest fix...
Actually, I think the simplest approach is to modify the functions to handle the extra dimension properly. The key insight is:
-
For teacher_topk_log_probs with nested shape [B, None, topk]:
input_ids[i] is a jagged tensor with S_i elements of shape [topk]
- We need to extract S_i sequence lengths
- After CP split, we need a tensor of shape [local_S_i, topk]
-
For input_ids with nested shape [B, None]:
input_ids[i] is a jagged tensor with S_i elements of shape [1] (scalar)
- We extract S_i sequence lengths
- After CP split, we need a tensor of shape [local_S_i]
The fix should detect the trailing dimensions and handle them appropriately.
Here's my approach for the fix:
def preprocess_bshd_engine(input_ids, pre_process=True, ...):
...
# Get the number of trailing dimensions beyond the jagged dimension
# For [B, None] -> 0 trailing dims
# For [B, None, topk] -> 1 trailing dim
extra_dim_size = None
if input_ids.numel() > 0 and hasattr(input_ids, 'values'):
values = input_ids.values()
if values.ndim > 1:
extra_dim_size = values.shape[1:] # Shape of trailing dimensions
...
Actually, this is getting complex. Let me think of a simpler approach.
The simplest fix might be to modify the call site in compute_forward_kl_topk to handle the extra dimension. Instead of passing the nested tensor directly, we could:
- For each topk position, extract the 1D sequences
- Apply
preprocess_bshd_engine to each
- Stack the results back
But this would be inefficient and complex.
A better approach would be to modify preprocess_bshd_engine to handle arbitrary trailing dimensions. Let me look at the function again and plan the fix.
Actually, looking at the problem from a different angle: the preprocess_bshd_engine function is designed for input_ids which are 1D sequences. But teacher_topk_log_probs has the same structure plus an extra topk dimension.
The key operations in preprocess_bshd_engine are:
- Computing sequence lengths (needs to be fixed for nested tensors with extra dims)
- Copying sequences to a regular tensor (needs to handle extra dims)
- Applying CP split (zigzag pattern)
For operation 1, the fix is to count the number of elements in each jagged sequence, not use .offsets().diff().
For operation 2, we need to handle the extra dimensions.
For operation 3, the zigzag pattern is the same regardless of extra dimensions.
Let me implement the fix:
def preprocess_bshd_engine(input_ids, pre_process=True, ...):
cp_size = mpu.get_context_parallel_world_size()
cp_rank = mpu.get_context_parallel_rank()
batch_size = input_ids.shape[0]
# Get sequence lengths: for jagged tensor with elements of shape [topk],
# we need to count the number of elements, not use .offsets().diff()
seqlens_in_batch = input_ids.size(-2) if input_ids.ndim > 1 else input_ids.offsets().diff()
Hmm, this is tricky because for a jagged tensor:
input_ids.size(0) gives the number of elements in the jagged sequence
- But
input_ids.ndim might be different depending on the layout
Let me check what input_ids.ndim is for a jagged tensor...
Actually, for a jagged nested tensor jt:
jt.ndim gives the number of dimensions including the jagged one
- If
jt represents elements of shape [topk], then jt.ndim = 2
- If
jt represents scalar elements, then jt.ndim = 1
But wait, that's not quite right either. For a jagged tensor:
jt.values() returns the flattened values with shape [total_elements * element_dim]
jt.ndim is undefined or returns something unexpected
I think I need to test this to understand the behavior. But for now, let me propose a fix based on my understanding.
Actually, I just realized something. The issue might be that I'm overthinking this. Let me re-read the issue:
teacher_topk_log_probs is [b, length, 64]
but preprocess_bshd_engine this function need [n, length] dim, so error happens
The user is saying:
- Input has shape
[b, length, 64]
preprocess_bshd_engine needs [n, length] dimension
Looking at preprocess_bshd_engine:
batch_size = input_ids.shape[0]
seqlens_in_batch = input_ids.offsets().diff()
It expects:
- First dimension = batch size (OK)
.offsets() to work (requires nested tensor)
.offsets().diff() to give sequence lengths
The issue is that the input has an extra dimension (64 = topk) that preprocess_bshd_engine doesn't expect.
So the fix is to handle the extra dimension. Here's my approach:
For a nested tensor with shape [B, None, 64]:
input_ids[i] is a jagged tensor with S elements of shape [64]
- We need to get S as the sequence length
- After CP split, we need shape
[local_S, 64]
The fix would be to:
- For each batch element
input_ids[i] (jagged tensor), get the number of elements
- Extract those elements (each of shape [64])
- Apply the CP split
- Concatenate into a tensor of shape
[local_S, 64]
Here's the fix for preprocess_bshd_engine:
def preprocess_bshd_engine(input_ids, pre_process=True, ...):
cp_size = mpu.get_context_parallel_world_size()
cp_rank = mpu.get_context_parallel_rank()
batch_size = input_ids.shape[0]
# Handle nested tensors with extra dimensions
# Get the number of elements in each batch item's jagged sequence
seqlens_in_batch = torch.tensor([jt.size(0) for jt in input_ids], device=input_ids.device)
...
Wait, input_ids.size(0) for a nested tensor gives the batch size, not the sequence lengths per batch item.
Let me think differently. For a nested tensor:
input_ids.shape = [B, None, topk]
input_ids[i] is a jagged tensor with shape [None, topk]
input_ids[i].size(0) for a jagged tensor gives the number of elements
Actually, I'm not sure if .size(0) works on a jagged tensor. Let me just iterate over the batch items and check.
OK here's my approach:
seqlens_in_batch = torch.zeros(batch_size, dtype=torch.int64, device=input_ids.device)
for i in range(batch_size):
seqlens_in_batch[i] = input_ids[i].size(0) # Number of elements in jagged tensor
But this assumes input_ids[i] is a jagged tensor with .size(0). I need to verify this works.
Alternatively, I can use:
seqlens_in_batch = input_ids._sizes() # Returns list of shapes for each batch item
Hmm, I'm not sure if _sizes() is public or works as expected.
Let me just propose a fix and test it. The key changes are:
- Extract sequence lengths correctly from the jagged tensor
- Handle extra dimensions when copying to the output tensor
Here's my proposed fix for preprocess_bshd_engine:
def preprocess_bshd_engine(input_ids, pre_process=True, ...):
cp_size = mpu.get_context_parallel_world_size()
cp_rank = mpu.get_context_parallel_rank()
batch_size = input_ids.shape[0]
# Determine if input has extra dimensions beyond the jagged sequence dimension
# For [B, None] -> no extra dims
# For [B, None, topk] -> 1 extra dim of size topk
# Get the shape of extra dimensions (if any)
if batch_size > 0:
first_item = input_ids[0] # Jagged tensor
# For a jagged tensor, values() gives flattened data
values = first_item.values()
extra_dim_size = values.shape[1:] if values.ndim > 1 else ()
else:
extra_dim_size = ()
# Get sequence lengths (number of elements in each jagged sequence)
seqlens_in_batch = torch.tensor([jt.size(0) if hasattr(jt, 'size') else 1 for jt in input_ids],
dtype=torch.int64, device=input_ids.device)
...
Wait, this is getting complicated. Let me look at the existing test to see how it handles nested tensors.
Actually, let me just try to run the existing test and see if it passes or fails:
<tool_call>
<function=bash_terminal>
<parameter=command>
cd /verl && find . -name "pytest.ini" -o -name "setup.py" -o -name "pyproject.toml" | head -5
</tool_call>