When I use the pip package marker-pdf and run marker_single jangrayhood.pdf, it shows…
- User
When I use the pip package
marker-pdfand runmarker_single jangrayhood.pdf, it showsRecognizing Layout: 0%| | 0/23 [00:00<?, ?it/s]num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 1 num_valid_tokens tensor([-4747009370887635497, 4325071974800047055, -4791057797432230261, -5043963192897847703, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') max_tokens 4325071974800047055 Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Python312\Scripts\marker_single.exe\__main__.py", line 10, in <module> File "C:\Python312\Lib\site-packages\click\core.py", line 1485, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\click\core.py", line 1406, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\click\core.py", line 1269, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\click\core.py", line 824, in invoke return callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\marker\scripts\convert_single.py", line 38, in convert_single_cli rendered = converter(fpath) ^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\marker\converters\pdf.py", line 195, in __call__ document = self.build_document(temp_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\marker\converters\pdf.py", line 182, in build_document document = DocumentBuilder(self.config)( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\marker\builders\document.py", line 33, in __call__ layout_builder(document, provider) File "C:\Python312\Lib\site-packages\marker\builders\layout.py", line 56, in __call__ layout_results = self.surya_layout(document.pages) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\marker\builders\layout.py", line 88, in surya_layout layout_results = self.layout_model( ^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\surya\layout\__init__.py", line 51, in __call__ self.foundation_predictor.prediction_loop( File "C:\Python312\Lib\site-packages\surya\foundation\__init__.py", line 827, in prediction_loop updated_inputs, outputs = self.decode( ^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\surya\foundation\__init__.py", line 341, in decode outputs = self.model( ^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1776, in _wrapped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1787, in _call_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\surya\common\surya\__init__.py", line 468, in forward outputs = self.decoder( ^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1776, in _wrapped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1787, in _call_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\surya\common\surya\decoder\__init__.py", line 504, in forward layer_outputs = decoder_layer( ^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1776, in _wrapped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1787, in _call_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\surya\common\surya\decoder\__init__.py", line 302, in forward hidden_states, self_attn_weights = self.self_attn( ^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1776, in _wrapped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\torch\nn\modules\module.py", line 1787, in _call_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\surya\common\surya\decoder\__init__.py", line 188, in forward key_states, value_states = past_key_value.update( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\surya\foundation\cache\dynamic_ops.py", line 83, in update return update_fn( ^^^^^^^^^^ File "C:\Python312\Lib\site-packages\surya\foundation\cache\dynamic_ops.py", line 360, in _decode_update offsets = torch.arange(max_tokens, device=device).unsqueeze(0) # [1, max_T] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RuntimeError: Storage size calculation overflowed with sizes=[4325071974800047104] Recognizing Layout: 0%| | 0/23 [00:03<?, ?it/s] Assistant
Looking at this crash, the root cause is clear from the output:
num_valid_tokens tensor([-4747009370887635497, 4325071974800047055, ...]) max_tokens 4325071974800047055The
num_valid_tokenstensor gets corrupted with garbage values (negative numbers, huge integers), and thenmax_tokensbecomes an astronomically large number. This is then passed totorch.arange(max_tokens, ...)which tries to allocate a tensor of size ~4.3 quintillion, causing the overflow.Let me trace through the code to find exactly where this corruption happens.
Assistant
I can see the crash site. Now let me trace where
num_valid_tokensis computed. The corruption happens in_decode_updateat line 356 wherenum_valid_tokens.max().item()returns a garbage value. I need to find wherenum_valid_tokensis set in thedecodemethod.Assistant
Now I can see the debug prints are already in the file (lines 357-359). The corruption happens at line 356 where
num_valid_tokens.max().item()returns a garbage value. Let me trace wherenum_valid_tokensoriginates. It comes fromcurrent_inputs.num_valid_tokensin thedecodemethod (line 329), and gets updated at line 378 viamaybe_insert_beacon_tokens. Let me look at the full flow more carefully.Assistant
Now let me look at the
_decode_updatemethod more carefully, and also understand thedecode_attention_mask_updateto see the full flow ofnum_valid_tokens.Assistant
Good. Now I see the full picture. The
num_valid_tokenstensor gets corrupted with garbage values. This is passed throughcache_kwargsfrom the model's forward pass. Let me trace hownum_valid_tokensflows through the model to find where the corruption originates.Assistant
Let me trace how
num_valid_tokensgets passed into the model and through the decoder layers.Assistant
Now let me see how the decoder layer passes
num_valid_tokensto the self-attention and then to the cache update.Assistant
Now I have the full picture. The
num_valid_tokenstensor is passed fromdecode()infoundation/__init__.py(line 329, 349) through the model forward, through each decoder layer, intocache_kwargs(line 184), and then into_decode_update(line 306).The key observation from the error output is that
num_valid_tokensis correct (all 1s) for the first ~14 iterations, and then suddenly becomes corrupted with garbage values like-4747009370887635497. This pattern — correct values followed by sudden garbage — is a classic symptom of uninitialized memory or tensor reuse/aliasing where a tensor's underlying storage gets overwritten.Let me look more carefully at how
num_valid_tokensis created and whether it could be aliased or mutated in-place.Assistant
Now let me look at the
maybe_insert_beacon_tokensmore carefully and also theContinuousBatchInputdataclass to understand the tensor lifecycle. The key question is: where doesnum_valid_tokensget its value between decode iterations?Assistant
Now let me look at the merge logic (lines 640-670) where
num_valid_tokensgets merged intocurrent_num_valid_tokens:Assistant
Now I have a clear understanding of the flow. Let me now focus on the
maybe_insert_beacon_tokensreturn value. At line 268, when no beacon is needed, it returnsnum_new_tokens.squeeze(1). And at line 307-311, when beacons are needed, it returnsvalid_token_countswhich is freshly created viatorch.where.The critical path is in
decode()at line 378:input_ids, input_boxes, num_valid_tokens = self.maybe_insert_beacon_tokens( input_ids, input_boxes, num_predicted_tokens, num_new_tokens )And
num_new_tokensat line 365-375 is either a clamped tensor (withkeepdim=True, shape[B, 1]) orinput_ids.shape[1](a plain int).When
max_lookahead_tokens is None(line 374),num_new_tokens = input_ids.shape[1]— an integer, not a tensor. Thenmaybe_insert_beacon_tokensreceivesnum_new_tokens=Noneeffectively... wait, no, it receives the int. Let me re-readmaybe_insert_beacon_tokens:Assistant
Now I have a very clear picture. Let me look at the
_decode_updateone more time to understand thetext_token_countsmutation at line 394:Assistant
Now I have the full picture. Let me analyze the root cause.
The
_decode_updateis called once per decoder layer (there are multiple layers). Each call receives the samenum_valid_tokenstensor fromcache_kwargs. At line 394:text_token_counts += num_valid_tokensThis is an in-place addition on
text_token_counts(which isself.text_token_counts[layer_idx]). This is fine — each layer has its owntext_token_counts.But the real issue is different. Let me look at the corruption pattern again:
num_valid_tokens tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0') # correct, 14 times num_valid_tokens tensor([-4747009370887635497, 4325071974800047055, ...]) # garbageThe tensor is correct for many iterations, then suddenly corrupted. This is a dtype issue. Let me check:
torch.whereat line 307 creates using and — these default to . But the at line 268 comes from where was computed at line 365-373 as a tensor.Assistant
Now let me look at the prediction loop more carefully — specifically the decode path (line 826-907) to understand the full iteration:
Assistant
Now I need to understand the full lifecycle. When a batch element finishes (line 903:
self.batch_prompt_mapping[b_idx] = None), its slot becomes empty. Then on the next iteration of the while loop, if there are queued prompts, it goes toprefillwhich merges new prompts into those slots. But if there are no queued prompts, it goes todecodewith the samecurrent_inputs— including thenum_valid_tokensfor the finished slots.But that shouldn't cause garbage values. The garbage pattern (
-4747009370887635497) looks like memory corruption — interpreting float/bf16 bits as int64.Let me think about this differently. The
num_valid_tokenstensor is created inmaybe_insert_beacon_tokens. When no beacon is needed (line 262-268), it returnsnum_new_tokens.squeeze(1).In the
decodemethod, at line 365-373 is:Assistant
No
torch.emptycalls. Let me reconsider. The garbage values innum_valid_tokenslook like this:tensor([-4747009370887635497, 4325071974800047055, -4791057797432230261, -5043963192897847703, 1, 1, 1, 1, 1, 1, 1, 1])Notice: the first 4 elements are garbage, the remaining 8 are correct (value 1). This is a batch of 12. This suggests that the first 4 batch elements have corrupted while the rest are fine.
Assistant
OK, so on CUDA it uses
torch.inference_mode. Let me think about this differently.The garbage values
-4747009370887635497, 4325071974800047055— let me check if these could be bf16 float values reinterpreted as int64. Actually, the pattern of 4 corrupted + 8 correct values in a batch of 12 is very telling.Let me look at the
decode_attention_mask_updatecall at line 333-334 — it's called before the model forward, using thenum_valid_tokensfrom the previous iteration. Then the model runs, and_decode_updateis called inside the model forward for each layer, also using the samenum_valid_tokens.But wait — the
num_valid_tokenspassed to the model at line 349 is the same tensor object as what was used at line 334. And inside_decode_update, at line 394:text_token_counts += num_valid_tokensThis is
text_token_counts += num_valid_tokens. This does NOT mutatenum_valid_tokens. It mutatestext_token_countsin-place. So that's fine.Let me look at this from yet another angle. Let me check the
process_outputsmethod and howscoresare computed:Assistant
Now let me look at the layout model specifically, since the crash happens during "Recognizing Layout". The layout model calls
prediction_loopwhich callsdecode. Let me check the layout builder:Assistant
Assistant
Let me look at the
beacon_token_intervalto understand when beacons get triggered, and also check if there's a potential issue with thenum_predicted_tokens += num_new_tokensin-place operation:Assistant
beacon_token_interval = 4096. Withmax_tokens=500for layout, beacons will never be triggered. Somaybe_insert_beacon_tokenswill always take the early return path at line 262-268, returningnum_new_tokens.squeeze(1).Let me now think about this more carefully. The
num_new_tokensis computed fresh each iteration fromprocessed_output.scores. It should always be valid. But the corruption happens in_decode_updatewhich receivesnum_valid_tokensfromcache_kwargs.Wait — I need to re-read the flow more carefully. In
decode():- Line 329:
num_valid_tokens = current_inputs.num_valid_tokens— this is the previous iteration'snum_valid_tokens - Line 333-334: — uses previous iteration's value
- Line 329:
Assistant
Can't run Python directly. Let me check the version from the package metadata:
Assistant
Let me try a different approach and look at the installed packages:
- User
Do a simple test of how to call the Python in Windows
C:\Python312\python.exeand run a simple script from your bash sandbox. There should be a way to escape Windows Python's path. Assistant
Found it. The Windows path
C:\Python312is accessible as/c/Python312in this bash environment.Assistant
Now I can run Python. Let me check the versions:
Assistant
Good. Now let me go back to the root cause analysis. Let me re-examine the corruption pattern more carefully.
The key insight:
num_valid_tokenshas 12 elements (batch_size=12), first 4 are garbage, last 8 are correct (value 1). The garbage values like-4747009370887635497interpreted as int64 — these look like they could be the result of reading uninitialized or freed memory.Let me now look at the
_decode_updatemore carefully. Thenum_valid_tokenscomes fromcache_kwargs["num_valid_tokens"]. This is the same tensor object passed through all decoder layers. The_decode_updateis called for each layer, and each call does at line 394. This is — it mutates , not .Assistant
Now I see the flow clearly. Each iteration:
updated_inputs, outputs = self.decode(current_inputs, ...)- Process
outputs current_inputs = updated_inputs(line 907)- Next iteration:
self.decode(current_inputs, ...)— usescurrent_inputs.num_valid_tokens
The
num_valid_tokensstored inupdated_inputswas created insidedecode()frommaybe_insert_beacon_tokens. Since beacons never trigger for layout (interval=4096, max_tokens=500), it always returnsnum_new_tokens.squeeze(1).num_new_tokensis computed fromprocessed_output.scoreswhich is computed fromoutputs["lm_logits"]— model output tensors. Under , PyTorch may reuse tensor storage more aggressively.Assistant
Now I see it clearly. For the layout model,
max_lookahead_tokens=0(from the layout call at line 56 oflayout/__init__.py). Somax_lookahead_tokens is not NoneisTrue, and we go into theifbranch at line 364.processed_output.scoreshas shape[B, T]. Withmax_lookahead_tokens=0,process_outputsat line 216-220 truncateslm_logitsto[:, :1, :], soT=1. Thenscoreshas shape[B, 1].So
num_new_tokens=torch.clamp(scores.ge(tau).to(torch.long).cumprod(dim=1).sum(dim=1, keepdim=True), min=1)— shape[B, 1], all values will be 1 (since there's only 1 token and clamp min=1).Assistant
Let me add strategic debug prints to the
decodemethod to see exactly when the corruption happens — is it already corrupted when enteringdecode, or does it get corrupted during the model forward pass?Assistant
Let me add debug prints at the start of
decodeand after the model forward to narrow down exactly when corruption happens:- User
Go on
Assistant
Good, the debug prints were already applied from the interrupted edit. Now let me also add a debug print after the model forward to see if
num_valid_tokensgets corrupted during the forward pass:- User
Go on
Assistant
Good, the debug print was applied. Now let me run the actual test to see when the corruption happens:
- User
There seems to be some issue with the sandbox when you run the test. Show what test you want to run.
Assistant
I want to run:
/c/Python312/python3 -m marker.scripts.convert_single jangrayhood.pdf 2>&1 | head -200But since the sandbox can't handle it (likely GPU/memory/timeout), let me take a different approach. Instead of running the test, let me reason through the code more carefully and look at the actual corruption mechanism.
Let me re-examine the key observation: the first 4 elements are garbage, the last 8 are 1. This is a batch of 12. In the
prediction_loop, when batch elements finish (EOS token), theirbatch_prompt_mapping[b_idx]is set toNone, but they remain in the batch. New prompts from the queue get prefilled into those slots.The critical question is: what happens to
num_valid_tokensfor slots that just got prefilled? Let me look at the merge path again:- User
Assistant
Excellent! This is very revealing. Let me analyze the output:
-
First decode call:
DECODE ENTRY→ all 1s,AFTER ATTN MASK UPDATE→ all 1s, all 12 layer_decode_updatecalls → all 1s,AFTER MODEL FORWARD→ all 1s. Everything fine. -
Second decode call:
DECODE ENTRY→ all 1s (new tensor, differentdata_ptr),AFTER ATTN MASK UPDATE→ all 1s, then the first 2_decode_updatelayer calls → all 1s, but the 3rd layer's_decode_updatesees corrupted values.
So the corruption happens during the model forward pass, between the 2nd and 3rd decoder layer's call. The same tensor is passed to all layers, and it gets corrupted mid-way through.
-
Assistant
Now let me trace exactly where
num_valid_tokensis created to apply the fix. The issue is inmaybe_insert_beacon_tokensat line 268 — it returnsnum_new_tokens.squeeze(1)which is a view. The fix is to.clone()it so it has its own memory that won't be reclaimed.But first, let me understand WHY the memory gets reclaimed.
num_new_tokensis stored as a local variable indecode(). It's passed tomaybe_insert_beacon_tokensand the returnednum_valid_tokens(a view of it) is stored inContinuousBatchInput. Sonum_new_tokensitself goes out of scope whendecode()returns, but the view (num_valid_tokens) should keep the underlying storage alive...- User
Go on
Assistant
Good, the
.clone()fix is applied. Now let me also remove the debug prints and clean up. But first, let me also check if there's a similar issue in the beacon path (line 307-313) — that path creates a fresh tensor viatorch.where, so it should be fine. But let me verify:Assistant
torch.wherecreates a new tensor (not a view), so the beacon path is fine. Now let me remove the debug prints:- User
It seems working for now. Now remove all debug edits.
Assistant
Let me find all the debug edits across the files.
Assistant
Good, 3 locations. Let me read the context around each debug print and remove them.
Assistant
Good, the
DECODE ENTRYandAFTER ATTN MASK UPDATEdebug prints were already removed. Now let me remove the remaining two debug prints:- User
Go on
Assistant
That debug print is already removed. Now let me remove the one in
dynamic_ops.py:- User
Explain why this fix is needed.
Assistant