1
0
Fork 0
mirror of https://github.com/p-e-w/heretic.git synced 2026-12-03 18:42:57 +07:00

[GH-ISSUE #89] Missing documentation - heretic hardware requirements #43

Closed
opened 2026-11-01 04:16:55 +07:00 by bsakaguchi · 20 comments
Owner

Originally created by @dagbdagb on GitHub (Dec 16, 2025).
Original GitHub issue: https://github.com/p-e-w/heretic/issues/89

Hi.

2 things I struggle to figure out on my own:

gpt-oss-120b and its smaller sibling come with weights in mxfp4 format.
Can I use Ampere hardware (rtx 3090) to decensor gpt-oss-120b? Cuda arch 86, so no native support for mxfp4. Does that matter?

Also, what are the hard memory requirements for successfully decensoring gpt-oss-120b? Is there a trivial way to calculate that? I see #83 , but still fail to grasp if less memory just means the process takes longer, or if it will fail.

Originally created by @dagbdagb on GitHub (Dec 16, 2025). Original GitHub issue: https://github.com/p-e-w/heretic/issues/89 Hi. 2 things I struggle to figure out on my own: gpt-oss-120b and its smaller sibling come with weights in mxfp4 format. Can I use Ampere hardware (rtx 3090) to decensor gpt-oss-120b? Cuda arch 86, so no native support for mxfp4. Does that matter? Also, what are the hard memory requirements for successfully decensoring gpt-oss-120b? Is there a trivial way to calculate that? I see #83 , but still fail to grasp if less memory just means the process takes longer, or if it will fail.
Author
Owner

@accemlcc commented on GitHub (Dec 17, 2025):

hey

Hardware Requirements for GPT-OSS-120B (MXFP4)

Short answer: No, RTX 3090 won't work. You need Hopper GPUs (H100) or newer.

Why RTX 3090 doesn't work:

  • MXFP4 requires Compute Capability ≥ 9.0 for native support
  • RTX 3090 has CC 8.6 (Ampere)
  • While transformers CAN dequantize to bf16, that defeats the purpose and requires massive VRAM

Anyways, it's already done and looks good:

https://huggingface.co/kldzj/gpt-oss-120b-heretic-v2
https://huggingface.co/bartowski/kldzj_gpt-oss-120b-heretic-v2-GGUF

<!-- gh-comment-id:3664863829 --> @accemlcc commented on GitHub (Dec 17, 2025): hey ### Hardware Requirements for GPT-OSS-120B (MXFP4) **Short answer: No, RTX 3090 won't work. You need Hopper GPUs (H100) or newer.** #### Why RTX 3090 doesn't work: - MXFP4 requires **Compute Capability ≥ 9.0** for native support - RTX 3090 has CC 8.6 (Ampere) - While transformers CAN dequantize to bf16, that defeats the purpose and requires massive VRAM --- Anyways, it's already done and looks good: https://huggingface.co/kldzj/gpt-oss-120b-heretic-v2 https://huggingface.co/bartowski/kldzj_gpt-oss-120b-heretic-v2-GGUF
Author
Owner

@dagbdagb commented on GitHub (Dec 17, 2025):

hey

Hardware Requirements for GPT-OSS-120B (MXFP4)

Short answer: No, RTX 3090 won't work. You need Hopper GPUs (H100) or newer.

Why RTX 3090 doesn't work:

  • MXFP4 requires Compute Capability ≥ 9.0 for native support
  • RTX 3090 has CC 8.6 (Ampere)
  • While transformers CAN dequantize to bf16, that defeats the purpose and requires massive VRAM

Anyways, it's already done and looks good:

https://huggingface.co/kldzj/gpt-oss-120b-heretic-v2 https://huggingface.co/bartowski/kldzj_gpt-oss-120b-heretic-v2-GGUF

The timestamp of those files suggest that they are missing a few fixes in heretic 1.1? Happy to be set straight if this is incorrect.

<!-- gh-comment-id:3665022503 --> @dagbdagb commented on GitHub (Dec 17, 2025): > hey > > ### Hardware Requirements for GPT-OSS-120B (MXFP4) > **Short answer: No, RTX 3090 won't work. You need Hopper GPUs (H100) or newer.** > > #### Why RTX 3090 doesn't work: > * MXFP4 requires **Compute Capability ≥ 9.0** for native support > * RTX 3090 has CC 8.6 (Ampere) > * While transformers CAN dequantize to bf16, that defeats the purpose and requires massive VRAM > > Anyways, it's already done and looks good: > > https://huggingface.co/kldzj/gpt-oss-120b-heretic-v2 https://huggingface.co/bartowski/kldzj_gpt-oss-120b-heretic-v2-GGUF The timestamp of those files suggest that they are missing a few fixes in heretic 1.1? Happy to be set straight if this is incorrect.
Author
Owner

@accemlcc commented on GitHub (Dec 17, 2025):

The timestamp of those files suggest that they are missing a few fixes in heretic 1.1? Happy to be set straight if this is incorrect.

Oops... you're right, they were made with the old version of Heretic. I was misled by V2, mea culpa.

<!-- gh-comment-id:3665078584 --> @accemlcc commented on GitHub (Dec 17, 2025): > The timestamp of those files suggest that they are missing a few fixes in heretic 1.1? Happy to be set straight if this is incorrect. Oops... you're right, they were made with the old version of Heretic. I was misled by V2, mea culpa.
Author
Owner

@accemlcc commented on GitHub (Dec 17, 2025):

If you still want to try it yourself: you would need at least two H100s, PyTorch 2.8, the latest Triton version and my #60, which also circumvents the 3D tensor problem.

<!-- gh-comment-id:3665166257 --> @accemlcc commented on GitHub (Dec 17, 2025): If you still want to try it yourself: you would need at least two H100s, PyTorch 2.8, the latest Triton version and my #60, which also circumvents the 3D tensor problem.
Author
Owner

@dagbdagb commented on GitHub (Dec 17, 2025):

Might have to look into how to rent hardware and stuff. Unlikely to happen while the calendar still says 2025.

<!-- gh-comment-id:3665316594 --> @dagbdagb commented on GitHub (Dec 17, 2025): Might have to look into how to rent hardware and stuff. Unlikely to happen while the calendar still says 2025.
Author
Owner

@dagbdagb commented on GitHub (Dec 19, 2025):

@accemlcc
At https://docs.unsloth.ai/models/gpt-oss-how-to-run-and-fine-tune , I find this little nugget:

"MXFP4 is not actually supported on Ampere and older GPUs, so Triton provides tl.dot_scaled for MXFP4 matrix multiplication. It upcasts the matrices to BF16 internaly on the fly."

Is this something which can be employed by heretic?

<!-- gh-comment-id:3674297203 --> @dagbdagb commented on GitHub (Dec 19, 2025): @accemlcc At https://docs.unsloth.ai/models/gpt-oss-how-to-run-and-fine-tune , I find this little nugget: "MXFP4 is not actually supported on Ampere and older GPUs, so Triton provides tl.dot_scaled for MXFP4 matrix multiplication. It upcasts the matrices to BF16 internaly on the fly." Is this something which can be employed by heretic?
Author
Owner

@accemlcc commented on GitHub (Dec 19, 2025):

@accemlcc At https://docs.unsloth.ai/models/gpt-oss-how-to-run-and-fine-tune , I find this little nugget:

"MXFP4 is not actually supported on Ampere and older GPUs, so Triton provides tl.dot_scaled for MXFP4 matrix multiplication. It upcasts the matrices to BF16 internaly on the fly."

Is this something which can be employed by heretic?

For clarification: Tools like LM Studio use GGUF, which is highly optimized for split CPU/GPU inference.

Heretic uses native PyTorch/Transformers.

More importantly: Heretic doesn't just generate text; it extracts hidden states (residuals) from the model to calculate vectors. This requires significantly more VRAM bandwidth and capacity than simple chat inference.

So while you might get 5 t/s chatting in GGUF, running an optimization loop in PyTorch with residual extraction on a single 3090 will likely result in OOMs or extreme slowness due to PCIe bottlenecks.

<!-- gh-comment-id:3674430920 --> @accemlcc commented on GitHub (Dec 19, 2025): > [@accemlcc](https://github.com/accemlcc) At https://docs.unsloth.ai/models/gpt-oss-how-to-run-and-fine-tune , I find this little nugget: > > "MXFP4 is not actually supported on Ampere and older GPUs, so Triton provides tl.dot_scaled for MXFP4 matrix multiplication. It upcasts the matrices to BF16 internaly on the fly." > > Is this something which can be employed by heretic? For clarification: Tools like LM Studio use GGUF, which is highly optimized for split CPU/GPU inference. Heretic uses native PyTorch/Transformers. More importantly: Heretic doesn't just generate text; it extracts hidden states (residuals) from the model to calculate vectors. This requires significantly more VRAM bandwidth and capacity than simple chat inference. So while you might get 5 t/s chatting in GGUF, running an optimization loop in PyTorch with residual extraction on a single 3090 will likely result in OOMs or extreme slowness due to PCIe bottlenecks.
Author
Owner

@dagbdagb commented on GitHub (Dec 19, 2025):

@accemlcc At https://docs.unsloth.ai/models/gpt-oss-how-to-run-and-fine-tune , I find this little nugget:
"MXFP4 is not actually supported on Ampere and older GPUs, so Triton provides tl.dot_scaled for MXFP4 matrix multiplication. It upcasts the matrices to BF16 internaly on the fly."
Is this something which can be employed by heretic?

For clarification: Tools like LM Studio use GGUF, which is highly optimized for split CPU/GPU inference.

Heretic uses native PyTorch/Transformers.

More importantly: Heretic doesn't just generate text; it extracts hidden states (residuals) from the model to calculate vectors. This requires significantly more VRAM bandwidth and capacity than simple chat inference.

So while you might get 5 t/s chatting in GGUF, running an optimization loop in PyTorch with residual extraction on a single 3090 will likely result in OOMs or extreme slowness due to PCIe bottlenecks.

Triton permits extending pytorch's 'native' features. And, in the case of unsloth, casting between MXFP4 and FP16 (and FP32) as required by the hardware at hand.

I do have multiple 3090s, but all connected either via TB3 or PCIe 4x. If system/GPU bandwidth is important for the performance of heretic, I accept it will be slow. Unlike for inferencing, where my setup regularly provides 110-120 t/s with an empty context. (gpt-oss-120b-UD-Q8_K_XL, all layers on GPU, potato PC)

So, is system/GPU bandwidth important for heretic? Moreso than compute performance or GPU memory bandwidth? Or would up/down-casting be a/the killer for performance?

What is the expected runtime for heretic with gpt-oss-120b with a single h200? Or, if 2 are required due to VRAM requirements, with two? Does performance scale somewhat linearly?

Despite being technically competent in many subjects, I find it hard to achieve anything but very superficial knowledge about LLMs/pytorch/transformer/triton. Too much stuff already out there, and the fire-hose runs at full blast with new stuff 24x7. I very much appreciate the patience exhibited explaining this.

@p-e-w
I suggest a little blurb is added to the default README about hardware requirements/suggestions and a guesstimate for approximate runtime.

<!-- gh-comment-id:3674680433 --> @dagbdagb commented on GitHub (Dec 19, 2025): > > [@accemlcc](https://github.com/accemlcc) At https://docs.unsloth.ai/models/gpt-oss-how-to-run-and-fine-tune , I find this little nugget: > > "MXFP4 is not actually supported on Ampere and older GPUs, so Triton provides tl.dot_scaled for MXFP4 matrix multiplication. It upcasts the matrices to BF16 internaly on the fly." > > Is this something which can be employed by heretic? > > For clarification: Tools like LM Studio use GGUF, which is highly optimized for split CPU/GPU inference. > > Heretic uses native PyTorch/Transformers. > > More importantly: Heretic doesn't just generate text; it extracts hidden states (residuals) from the model to calculate vectors. This requires significantly more VRAM bandwidth and capacity than simple chat inference. > > So while you might get 5 t/s chatting in GGUF, running an optimization loop in PyTorch with residual extraction on a single 3090 will likely result in OOMs or extreme slowness due to PCIe bottlenecks. Triton permits extending pytorch's 'native' features. And, in the case of unsloth, casting between MXFP4 and FP16 (and FP32) as required by the hardware at hand. I do have multiple 3090s, but all connected either via TB3 or PCIe 4x. If system/GPU bandwidth is important for the performance of heretic, I accept it will be slow. Unlike for inferencing, where my setup regularly provides 110-120 t/s with an empty context. (gpt-oss-120b-UD-Q8_K_XL, all layers on GPU, potato PC) So, **is** system/GPU bandwidth important for heretic? Moreso than compute performance or GPU memory bandwidth? Or would up/down-casting be a/the killer for performance? What is the expected runtime for heretic with gpt-oss-120b with a single h200? Or, if 2 are required due to VRAM requirements, with two? Does performance scale somewhat linearly? Despite being technically competent in many subjects, I find it hard to achieve anything but very superficial knowledge about LLMs/pytorch/transformer/triton. Too much stuff already out there, and the fire-hose runs at full blast with new stuff 24x7. I very much appreciate the patience exhibited explaining this. @p-e-w I suggest a little blurb is added to the default README about hardware requirements/suggestions and a guesstimate for approximate runtime.
Author
Owner

@accemlcc commented on GitHub (Dec 19, 2025):

@dagbdagb

Okay, that context helps.

Regarding the Unsloth/Triton integration: That is a significant architectural decision at @p-e-w 's discretion. I will not be implementing it.

Regarding the H200: A full run should take less than 1 hour.

<!-- gh-comment-id:3674777814 --> @accemlcc commented on GitHub (Dec 19, 2025): @dagbdagb Okay, that context helps. Regarding the Unsloth/Triton integration: That is a significant architectural decision at @p-e-w 's discretion. I will not be implementing it. Regarding the H200: A full run should take less than 1 hour.
Author
Owner

@p-e-w commented on GitHub (Dec 19, 2025):

Heretic uses Transformers to perform inference, so Heretic's hardware requirements are exactly the same as those for running the model with Transformers. I have no intention to add more details to the README regarding that, as that would replicate information that is already available all over the web and can be highly specific to individual setups.

What is the expected runtime for heretic with gpt-oss-120b with a single h200?

That depends on the configuration (prompt datasets, n_trials, max_response_length etc.). Heretic estimates remaining runtime during optimization, so you can just try it and it will tell you.

<!-- gh-comment-id:3675177010 --> @p-e-w commented on GitHub (Dec 19, 2025): Heretic uses Transformers to perform inference, so Heretic's hardware requirements are exactly the same as those for running the model with Transformers. I have no intention to add more details to the README regarding that, as that would replicate information that is already available all over the web and can be highly specific to individual setups. > What is the expected runtime for heretic with gpt-oss-120b with a single h200? That depends on the configuration (prompt datasets, `n_trials`, `max_response_length` etc.). Heretic estimates remaining runtime during optimization, so you can just try it and it will tell you.
Author
Owner

@dagbdagb commented on GitHub (Dec 19, 2025):

Heretic uses Transformers to perform inference, so Heretic's hardware requirements are exactly the same as those for running the model with Transformers. I have no intention to add more details to the README regarding that, as that would replicate information that is already available all over the web and can be highly specific to individual setups.

What is the expected runtime for heretic with gpt-oss-120b with a single h200?

That depends on the configuration (prompt datasets, n_trials, max_response_length etc.). Heretic estimates remaining runtime during optimization, so you can just try it and it will tell you.

Thank you. And thank you for heretic.

<!-- gh-comment-id:3675185723 --> @dagbdagb commented on GitHub (Dec 19, 2025): > Heretic uses Transformers to perform inference, so Heretic's hardware requirements are exactly the same as those for running the model with Transformers. I have no intention to add more details to the README regarding that, as that would replicate information that is already available all over the web and can be highly specific to individual setups. > > > What is the expected runtime for heretic with gpt-oss-120b with a single h200? > > That depends on the configuration (prompt datasets, `n_trials`, `max_response_length` etc.). Heretic estimates remaining runtime during optimization, so you can just try it and it will tell you. Thank you. And thank you for heretic.
Author
Owner

@dagbdagb commented on GitHub (Dec 22, 2025):

Happy to report that heretic 1.1 did the job on gpt-oss-20b with 4x RTX3090, despite the lack of hw-support for mxfp4.

Elapsed time: 2h 6m
Refusals: 24/100, KL divergence: 0.1771

Had to set export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True.

Edit:
The saved safetensors weigh in at 39.0GB total (original: 11.9GB). I assume pytorch has converted the original mxfp4 to f16 on the fly, or something along that line.

<!-- gh-comment-id:3684576547 --> @dagbdagb commented on GitHub (Dec 22, 2025): Happy to report that heretic 1.1 did the job on gpt-oss-20b with 4x RTX3090, despite the lack of hw-support for mxfp4. Elapsed time: 2h 6m Refusals: 24/100, KL divergence: 0.1771 Had to set `export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`. Edit: The saved safetensors weigh in at 39.0GB total (original: 11.9GB). I assume pytorch has converted the original mxfp4 to f16 on the fly, or something along that line.
Author
Owner

@p-e-w commented on GitHub (Dec 28, 2025):

@dagbdagb

Had to set export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True.

This is already set on startup:

github.com/p-e-w/heretic@02a5237a02/src/heretic/main.py (L122-L127)

Are you sure that was necessary to set again manually? Because that would be a bug.

<!-- gh-comment-id:3694712706 --> @p-e-w commented on GitHub (Dec 28, 2025): @dagbdagb > Had to set export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True. This is already set on startup: https://github.com/p-e-w/heretic/blob/02a5237a0213f631370751550f283034042888f9/src/heretic/main.py#L122-L127 Are you sure that was necessary to set again manually? Because that would be a bug.
Author
Owner

@dagbdagb commented on GitHub (Dec 28, 2025):

I am quite sure that was the only change I did between a failed run and a successful run, yes. Should your and be an or?

<!-- gh-comment-id:3694726236 --> @dagbdagb commented on GitHub (Dec 28, 2025): I am quite sure that was the only change I did between a failed run and a successful run, yes. Should your *and* be an *or*?
Author
Owner

@p-e-w commented on GitHub (Dec 28, 2025):

No, it needs to be and, because the latter name is deprecated but still supported, so if either of the names is present we should not override the user's choice.

Are you using an older PyTorch version that doesn't support the new name yet?

<!-- gh-comment-id:3694803725 --> @p-e-w commented on GitHub (Dec 28, 2025): No, it needs to be `and`, because the latter name is deprecated but still supported, so if either of the names is present we should not override the user's choice. Are you using an older PyTorch version that doesn't support the new name yet?
Author
Owner

@dagbdagb commented on GitHub (Dec 28, 2025):

Re-reading the code in question without having my mind on other things makes my question appear stupid. My bad.

Anyways, I check my command history. It looks like this:

381 heretic openai/gpt-oss-20b
382 heretic openai/gpt-oss-20b
383 export CUDA_VISIBLE_DEVICES=0,1,2,3
384 heretic openai/gpt-oss-20b
385 export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
386 heretic openai/gpt-oss-20b

redoing this sequence from 383:

384 yields:


Determining optimal batch size...
* Trying batch size 1... Ok (16 tokens/s)
* Trying batch size 2... Ok (31 tokens/s)
* Trying batch size 4... Ok (59 tokens/s)
* Trying batch size 8... Ok (109 tokens/s)
* Trying batch size 16... Ok (183 tokens/s)
* Trying batch size 32... Ok (285 tokens/s)
* Trying batch size 64... Ok (396 tokens/s)
* Trying batch size 128... Failed (CUDA out of memory. Tried to allocate 5.27 GiB. GPU 0 has a total capacity of 23.55 GiB of which 
1.95 GiB is free. Including non-PyTorch memory, this process has 21.59 GiB memory in use. Of the 
allocated memory 17.17 GiB is allocated by PyTorch, and 4.10 GiB is reserved by PyTorch but unallocated. 
If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True 
to avoid fragmentation.  See documentation for Memory Management  
(https://pytorch.org/docs/stable/notes/cuda.html#environment-variables))
* Chosen batch size: 64

Checking for common response prefix...
* Prefix found: '<|channel|>analysis<|message|><|end|><|start|>assistant<|channel|>final<|message|>'

Loading good evaluation prompts from mlabonne/harmless_alpaca...
* 100 prompts loaded
* Obtaining first-token probability distributions...

Loading bad evaluation prompts from mlabonne/harmful_behaviors...
* 100 prompts loaded
* Counting model refusals...
* Initial refusals: 98/100

Calculating per-layer refusal directions...
* Obtaining residuals for good prompts...
╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮
│ /home/dagb/gits/heretic/.venv/bin/heretic:10 in <module>                                         │
│                                                                                                  │
│    7 │   │   sys.argv[0] = sys.argv[0][:-11]                                                     │
│    8 │   elif sys.argv[0].endswith(".exe"):                                                      │
│    9 │   │   sys.argv[0] = sys.argv[0][:-4]                                                      │
│ ❱ 10 │   sys.exit(main())                                                                        │
│   11                                                                                             │
│                                                                                                  │
│ /home/dagb/gits/heretic/src/heretic/main.py:747 in main                                          │
│                                                                                                  │
│   744 │   install()                                                                              │
│   745 │                                                                                          │
│   746 │   try:                                                                                   │
│ ❱ 747 │   │   run()                                                                              │
│   748 │   except BaseException as error:                                                         │
│   749 │   │   # Transformers appears to handle KeyboardInterrupt (or BaseException)              │
│   750 │   │   # internally in some places, which can re-raise a different error in the handler   │
│                                                                                                  │
│ /home/dagb/gits/heretic/src/heretic/main.py:322 in run                                           │
│                                                                                                  │
│   319 │   print()                                                                                │
│   320 │   print("Calculating per-layer refusal directions...")                                   │
│   321 │   print("* Obtaining residuals for good prompts...")                                     │
│ ❱ 322 │   good_residuals = model.get_residuals_batched(good_prompts)                             │
│   323 │   print("* Obtaining residuals for bad prompts...")                                      │
│   324 │   bad_residuals = model.get_residuals_batched(bad_prompts)                               │
│   325 │   refusal_directions = F.normalize(                                                      │
│                                                                                                  │
│ /home/dagb/gits/heretic/src/heretic/model.py:566 in get_residuals_batched                        │
│                                                                                                  │
│   563 │   │   residuals = []                                                                     │
│   564 │   │                                                                                      │
│   565 │   │   for batch in batchify(prompts, self.settings.batch_size):                          │
│ ❱ 566 │   │   │   residuals.append(self.get_residuals(batch))                                    │
│   567 │   │                                                                                      │
│   568 │   │   return torch.cat(residuals, dim=0)                                                 │
│   569                                                                                            │
│                                                                                                  │
│ /home/dagb/gits/heretic/src/heretic/model.py:534 in get_residuals                                │
│                                                                                                  │
│   531 │   def get_residuals(self, prompts: list[str]) -> Tensor:                                 │
│   532 │   │   # We only generate one token, and we return the residual vectors                   │
│   533 │   │   # at that token position, for each prompt and layer.                               │
│ ❱ 534 │   │   _, outputs = self.generate(                                                        │
│   535 │   │   │   prompts,                                                                       │
│   536 │   │   │   max_new_tokens=1,                                                              │
│   537 │   │   │   output_hidden_states=True,                                                     │
│                                                                                                  │
│ /home/dagb/gits/heretic/src/heretic/model.py:500 in generate                                     │
│                                                                                                  │
│   497 │   │                                                                                      │
│   498 │   │   # FIXME: The type checker has been disabled here because of the extremely comple   │
│   499 │   │   #        interplay between different generate() signatures and dynamic delegatio   │
│ ❱ 500 │   │   outputs = self.model.generate(                                                     │
│   501 │   │   │   **inputs,                                                                      │
│   502 │   │   │   **kwargs,                                                                      │
│   503 │   │   │   pad_token_id=self.tokenizer.pad_token_id,                                      │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/peft/peft_model.py:2048 in generate   │
│                                                                                                  │
│   2045 │   │   │   │   kwargs = get_alora_offsets_for_generate(self, *args, **kwargs)            │
│   2046 │   │   │   │   with self._enable_peft_forward_hooks(*args, **kwargs):                    │
│   2047 │   │   │   │   │   kwargs = {k: v for k, v in kwargs.items() if k not in self.special_p  │
│ ❱ 2048 │   │   │   │   │   outputs = self.base_model.generate(*args, **kwargs)                   │
│   2049 │   │   │   else:                                                                         │
│   2050 │   │   │   │   outputs = self.base_model.generate(**kwargs)                              │
│   2051 │   │   except:                                                                           │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/utils/_contextlib.py:120 in     │
│ decorate_context                                                                                 │
│                                                                                                  │
│   117 │   @functools.wraps(func)                                                                 │
│   118 │   def decorate_context(*args, **kwargs):                                                 │
│   119 │   │   with ctx_factory():                                                                │
│ ❱ 120 │   │   │   return func(*args, **kwargs)                                                   │
│   121 │                                                                                          │
│   122 │   return decorate_context                                                                │
│   123                                                                                            │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/generation/utils.py:2564 │
│ in generate                                                                                      │
│                                                                                                  │
│   2561 │   │   model_kwargs["use_cache"] = generation_config.use_cache                           │
│   2562 │   │                                                                                     │
│   2563 │   │   # 9. Call generation mode                                                         │
│ ❱ 2564 │   │   result = decoding_method(                                                         │
│   2565 │   │   │   self,                                                                         │
│   2566 │   │   │   input_ids,                                                                    │
│   2567 │   │   │   logits_processor=prepared_logits_processor,                                   │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/generation/utils.py:2784 │
│ in _sample                                                                                       │
│                                                                                                  │
│   2781 │   │   │   model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)  │
│   2782 │   │   │                                                                                 │
│   2783 │   │   │   if is_prefill:                                                                │
│ ❱ 2784 │   │   │   │   outputs = self(**model_inputs, return_dict=True)                          │
│   2785 │   │   │   │   is_prefill = False                                                        │
│   2786 │   │   │   else:                                                                         │
│   2787 │   │   │   │   outputs = model_forward(**model_inputs, return_dict=True)                 │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1775 in    │
│ _wrapped_call_impl                                                                               │
│                                                                                                  │
│   1772 │   │   if self._compiled_call_impl is not None:                                          │
│   1773 │   │   │   return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]        │
│   1774 │   │   else:                                                                             │
│ ❱ 1775 │   │   │   return self._call_impl(*args, **kwargs)                                       │
│   1776 │                                                                                         │
│   1777 │   # torchrec tests the code consistency with the following code                         │
│   1778 │   # fmt: off                                                                            │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1786 in    │
│ _call_impl                                                                                       │
│                                                                                                  │
│   1783 │   │   if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks   │
│   1784 │   │   │   │   or _global_backward_pre_hooks or _global_backward_hooks                   │
│   1785 │   │   │   │   or _global_forward_hooks or _global_forward_pre_hooks):                   │
│ ❱ 1786 │   │   │   return forward_call(*args, **kwargs)                                          │
│   1787 │   │                                                                                     │
│   1788 │   │   result = None                                                                     │
│   1789 │   │   called_always_called_hooks = set()                                                │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/accelerate/hooks.py:175 in            │
│ new_forward                                                                                      │
│                                                                                                  │
│   172 │   │   │   with torch.no_grad():                                                          │
│   173 │   │   │   │   output = module._old_forward(*args, **kwargs)                              │
│   174 │   │   else:                                                                              │
│ ❱ 175 │   │   │   output = module._old_forward(*args, **kwargs)                                  │
│   176 │   │   return module._hf_hook.post_forward(module, output)                                │
│   177 │                                                                                          │
│   178 │   # Overriding a GraphModuleImpl forward freezes the forward call and later modificati   │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/utils/generic.py:918 in  │
│ wrapper                                                                                          │
│                                                                                                  │
│    915 │   │   return_dict_passed = kwargs.pop("return_dict", return_dict)                       │
│    916 │   │   if return_dict_passed is not None:                                                │
│    917 │   │   │   return_dict = return_dict_passed                                              │
│ ❱  918 │   │   output = func(self, *args, **kwargs)                                              │
│    919 │   │   if not return_dict and not isinstance(output, tuple):                             │
│    920 │   │   │   output = output.to_tuple()                                                    │
│    921 │   │   return output                                                                     │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/modeling_ │
│ gpt_oss.py:668 in forward                                                                        │
│                                                                                                  │
│   665 │   │   )                                                                                  │
│   666 │   │                                                                                      │
│   667 │   │   # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)    │
│ ❱ 668 │   │   outputs: MoeModelOutputWithPast = self.model(                                      │
│   669 │   │   │   input_ids=input_ids,                                                           │
│   670 │   │   │   attention_mask=attention_mask,                                                 │
│   671 │   │   │   position_ids=position_ids,                                                     │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1775 in    │
│ _wrapped_call_impl                                                                               │
│                                                                                                  │
│   1772 │   │   if self._compiled_call_impl is not None:                                          │
│   1773 │   │   │   return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]        │
│   1774 │   │   else:                                                                             │
│ ❱ 1775 │   │   │   return self._call_impl(*args, **kwargs)                                       │
│   1776 │                                                                                         │
│   1777 │   # torchrec tests the code consistency with the following code                         │
│   1778 │   # fmt: off                                                                            │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1786 in    │
│ _call_impl                                                                                       │
│                                                                                                  │
│   1783 │   │   if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks   │
│   1784 │   │   │   │   or _global_backward_pre_hooks or _global_backward_hooks                   │
│   1785 │   │   │   │   or _global_forward_hooks or _global_forward_pre_hooks):                   │
│ ❱ 1786 │   │   │   return forward_call(*args, **kwargs)                                          │
│   1787 │   │                                                                                     │
│   1788 │   │   result = None                                                                     │
│   1789 │   │   called_always_called_hooks = set()                                                │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/utils/generic.py:1072 in │
│ wrapper                                                                                          │
│                                                                                                  │
│   1069 │   │   │   │   │   │   │   monkey_patched_layers.append((module, original_forward))      │
│   1070 │   │   │                                                                                 │
│   1071 │   │   │   try:                                                                          │
│ ❱ 1072 │   │   │   │   outputs = func(self, *args, **kwargs)                                     │
│   1073 │   │   │   except TypeError as original_exception:                                       │
│   1074 │   │   │   │   # If we get a TypeError, it's possible that the model is not receiving t  │
│   1075 │   │   │   │   # Get a TypeError even after removing the recordable kwargs -> re-raise   │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/modeling_ │
│ gpt_oss.py:507 in forward                                                                        │
│                                                                                                  │
│   504 │   │   position_embeddings = self.rotary_emb(hidden_states, position_ids)                 │
│   505 │   │                                                                                      │
│   506 │   │   for decoder_layer in self.layers:                                                  │
│ ❱ 507 │   │   │   hidden_states = decoder_layer(                                                 │
│   508 │   │   │   │   hidden_states,                                                             │
│   509 │   │   │   │   attention_mask=causal_mask_mapping[decoder_layer.attention_type],          │
│   510 │   │   │   │   position_ids=position_ids,                                                 │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/modeling_layers.py:94 in │
│ __call__                                                                                         │
│                                                                                                  │
│    91 │   │   │   │   logger.warning_once(message)                                               │
│    92 │   │   │                                                                                  │
│    93 │   │   │   return self._gradient_checkpointing_func(partial(super().__call__, **kwargs)   │
│ ❱  94 │   │   return super().__call__(*args, **kwargs)                                           │
│    95                                                                                            │
│    96                                                                                            │
│    97 @auto_docstring                                                                            │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1775 in    │
│ _wrapped_call_impl                                                                               │
│                                                                                                  │
│   1772 │   │   if self._compiled_call_impl is not None:                                          │
│   1773 │   │   │   return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]        │
│   1774 │   │   else:                                                                             │
│ ❱ 1775 │   │   │   return self._call_impl(*args, **kwargs)                                       │
│   1776 │                                                                                         │
│   1777 │   # torchrec tests the code consistency with the following code                         │
│   1778 │   # fmt: off                                                                            │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1786 in    │
│ _call_impl                                                                                       │
│                                                                                                  │
│   1783 │   │   if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks   │
│   1784 │   │   │   │   or _global_backward_pre_hooks or _global_backward_hooks                   │
│   1785 │   │   │   │   or _global_forward_hooks or _global_forward_pre_hooks):                   │
│ ❱ 1786 │   │   │   return forward_call(*args, **kwargs)                                          │
│   1787 │   │                                                                                     │
│   1788 │   │   result = None                                                                     │
│   1789 │   │   called_always_called_hooks = set()                                                │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/utils/generic.py:1031 in │
│ wrapped_forward                                                                                  │
│                                                                                                  │
│   1028 │   │   │   │   │   │   ):                                                                │
│   1029 │   │   │   │   │   │   │   output = orig_forward(*args, **kwargs)                        │
│   1030 │   │   │   │   │   else:                                                                 │
│ ❱ 1031 │   │   │   │   │   │   output = orig_forward(*args, **kwargs)                            │
│   1032 │   │   │   │   │   if not isinstance(output, tuple):                                     │
│   1033 │   │   │   │   │   │   collected_outputs[key] += (output,)                               │
│   1034 │   │   │   │   │   elif output[index] is not None:                                       │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/accelerate/hooks.py:175 in            │
│ new_forward                                                                                      │
│                                                                                                  │
│   172 │   │   │   with torch.no_grad():                                                          │
│   173 │   │   │   │   output = module._old_forward(*args, **kwargs)                              │
│   174 │   │   else:                                                                              │
│ ❱ 175 │   │   │   output = module._old_forward(*args, **kwargs)                                  │
│   176 │   │   return module._hf_hook.post_forward(module, output)                                │
│   177 │                                                                                          │
│   178 │   # Overriding a GraphModuleImpl forward freezes the forward call and later modificati   │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/utils/deprecation.py:172 │
│ in wrapped_func                                                                                  │
│                                                                                                  │
│   169 │   │   │   │   # DeprecationWarning is ignored by default, so we use FutureWarning inst   │
│   170 │   │   │   │   warnings.warn(message, FutureWarning, stacklevel=2)                        │
│   171 │   │   │                                                                                  │
│ ❱ 172 │   │   │   return func(*args, **kwargs)                                                   │
│   173 │   │                                                                                      │
│   174 │   │   return wrapped_func                                                                │
│   175                                                                                            │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/modeling_ │
│ gpt_oss.py:386 in forward                                                                        │
│                                                                                                  │
│   383 │   │   # Fully Connected                                                                  │
│   384 │   │   residual = hidden_states                                                           │
│   385 │   │   hidden_states = self.post_attention_layernorm(hidden_states)                       │
│ ❱ 386 │   │   hidden_states, _ = self.mlp(hidden_states)  # diff with llama: router scores       │
│   387 │   │   hidden_states = residual + hidden_states                                           │
│   388 │   │   return hidden_states                                                               │
│   389                                                                                            │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1775 in    │
│ _wrapped_call_impl                                                                               │
│                                                                                                  │
│   1772 │   │   if self._compiled_call_impl is not None:                                          │
│   1773 │   │   │   return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]        │
│   1774 │   │   else:                                                                             │
│ ❱ 1775 │   │   │   return self._call_impl(*args, **kwargs)                                       │
│   1776 │                                                                                         │
│   1777 │   # torchrec tests the code consistency with the following code                         │
│   1778 │   # fmt: off                                                                            │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1786 in    │
│ _call_impl                                                                                       │
│                                                                                                  │
│   1783 │   │   if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks   │
│   1784 │   │   │   │   or _global_backward_pre_hooks or _global_backward_hooks                   │
│   1785 │   │   │   │   or _global_forward_hooks or _global_forward_pre_hooks):                   │
│ ❱ 1786 │   │   │   return forward_call(*args, **kwargs)                                          │
│   1787 │   │                                                                                     │
│   1788 │   │   result = None                                                                     │
│   1789 │   │   called_always_called_hooks = set()                                                │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/accelerate/hooks.py:175 in            │
│ new_forward                                                                                      │
│                                                                                                  │
│   172 │   │   │   with torch.no_grad():                                                          │
│   173 │   │   │   │   output = module._old_forward(*args, **kwargs)                              │
│   174 │   │   else:                                                                              │
│ ❱ 175 │   │   │   output = module._old_forward(*args, **kwargs)                                  │
│   176 │   │   return module._hf_hook.post_forward(module, output)                                │
│   177 │                                                                                          │
│   178 │   # Overriding a GraphModuleImpl forward freezes the forward call and later modificati   │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/modeling_ │
│ gpt_oss.py:170 in forward                                                                        │
│                                                                                                  │
│   167 │                                                                                          │
│   168 │   def forward(self, hidden_states):                                                      │
│   169 │   │   router_scores, router_indices = self.router(hidden_states)  # (num_experts, seq_   │
│ ❱ 170 │   │   routed_out = self.experts(hidden_states, router_indices=router_indices, routing_   │
│   171 │   │   return routed_out, router_scores                                                   │
│   172                                                                                            │
│   173                                                                                            │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1775 in    │
│ _wrapped_call_impl                                                                               │
│                                                                                                  │
│   1772 │   │   if self._compiled_call_impl is not None:                                          │
│   1773 │   │   │   return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]        │
│   1774 │   │   else:                                                                             │
│ ❱ 1775 │   │   │   return self._call_impl(*args, **kwargs)                                       │
│   1776 │                                                                                         │
│   1777 │   # torchrec tests the code consistency with the following code                         │
│   1778 │   # fmt: off                                                                            │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1786 in    │
│ _call_impl                                                                                       │
│                                                                                                  │
│   1783 │   │   if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks   │
│   1784 │   │   │   │   or _global_backward_pre_hooks or _global_backward_hooks                   │
│   1785 │   │   │   │   or _global_forward_hooks or _global_forward_pre_hooks):                   │
│ ❱ 1786 │   │   │   return forward_call(*args, **kwargs)                                          │
│   1787 │   │                                                                                     │
│   1788 │   │   result = None                                                                     │
│   1789 │   │   called_always_called_hooks = set()                                                │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/accelerate/hooks.py:175 in            │
│ new_forward                                                                                      │
│                                                                                                  │
│   172 │   │   │   with torch.no_grad():                                                          │
│   173 │   │   │   │   output = module._old_forward(*args, **kwargs)                              │
│   174 │   │   else:                                                                              │
│ ❱ 175 │   │   │   output = module._old_forward(*args, **kwargs)                                  │
│   176 │   │   return module._hf_hook.post_forward(module, output)                                │
│   177 │                                                                                          │
│   178 │   # Overriding a GraphModuleImpl forward freezes the forward call and later modificati   │
│                                                                                                  │
│ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/modeling_ │
│ gpt_oss.py:130 in forward                                                                        │
│                                                                                                  │
│   127 │   │   else:                                                                              │
│   128 │   │   │   hidden_states = hidden_states.repeat(num_experts, 1)                           │
│   129 │   │   │   hidden_states = hidden_states.view(num_experts, -1, self.hidden_size)          │
│ ❱ 130 │   │   │   gate_up = torch.bmm(hidden_states, self.gate_up_proj) + self.gate_up_proj_bi   │
│   131 │   │   │   gate, up = gate_up[..., ::2], gate_up[..., 1::2]                               │
│   132 │   │   │   gate = gate.clamp(min=None, max=self.limit)                                    │
│   133 │   │   │   up = up.clamp(min=-self.limit, max=self.limit)                                 │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
OutOfMemoryError: CUDA out of memory. Tried to allocate 2.84 GiB. GPU 0 has a total capacity of 23.55 GiB
of which 1.95 GiB is free. Including non-PyTorch memory, this process has 21.59 GiB memory in use. Of the
allocated memory 13.38 GiB is allocated by PyTorch, and 7.89 GiB is reserved by PyTorch but unallocated. 
If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True 
to avoid fragmentation.  See documentation for Memory Management  
(https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)
(heretic) dagb@p53 ~/gits/heretic $ 

386 powers through:

....

Calculating per-layer refusal directions...
* Obtaining residuals for good prompts...
* Obtaining residuals for bad prompts...

Running trial 1 of 200...
* Parameters:
  * direction_index = per layer
  * attn.o_proj.max_weight = 1.39
  * attn.o_proj.max_weight_position = 20.98
  * ....

<!-- gh-comment-id:3694906669 --> @dagbdagb commented on GitHub (Dec 28, 2025): Re-reading the code in question without having my mind on other things makes my question appear stupid. My bad. Anyways, I check my command history. It looks like this: 381 heretic openai/gpt-oss-20b 382 heretic openai/gpt-oss-20b 383 export CUDA_VISIBLE_DEVICES=0,1,2,3 384 heretic openai/gpt-oss-20b 385 export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True 386 heretic openai/gpt-oss-20b redoing this sequence from 383: 384 yields: ``` Determining optimal batch size... * Trying batch size 1... Ok (16 tokens/s) * Trying batch size 2... Ok (31 tokens/s) * Trying batch size 4... Ok (59 tokens/s) * Trying batch size 8... Ok (109 tokens/s) * Trying batch size 16... Ok (183 tokens/s) * Trying batch size 32... Ok (285 tokens/s) * Trying batch size 64... Ok (396 tokens/s) * Trying batch size 128... Failed (CUDA out of memory. Tried to allocate 5.27 GiB. GPU 0 has a total capacity of 23.55 GiB of which 1.95 GiB is free. Including non-PyTorch memory, this process has 21.59 GiB memory in use. Of the allocated memory 17.17 GiB is allocated by PyTorch, and 4.10 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)) * Chosen batch size: 64 Checking for common response prefix... * Prefix found: '<|channel|>analysis<|message|><|end|><|start|>assistant<|channel|>final<|message|>' Loading good evaluation prompts from mlabonne/harmless_alpaca... * 100 prompts loaded * Obtaining first-token probability distributions... Loading bad evaluation prompts from mlabonne/harmful_behaviors... * 100 prompts loaded * Counting model refusals... * Initial refusals: 98/100 Calculating per-layer refusal directions... * Obtaining residuals for good prompts... ╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮ │ /home/dagb/gits/heretic/.venv/bin/heretic:10 in <module> │ │ │ │ 7 │ │ sys.argv[0] = sys.argv[0][:-11] │ │ 8 │ elif sys.argv[0].endswith(".exe"): │ │ 9 │ │ sys.argv[0] = sys.argv[0][:-4] │ │ ❱ 10 │ sys.exit(main()) │ │ 11 │ │ │ │ /home/dagb/gits/heretic/src/heretic/main.py:747 in main │ │ │ │ 744 │ install() │ │ 745 │ │ │ 746 │ try: │ │ ❱ 747 │ │ run() │ │ 748 │ except BaseException as error: │ │ 749 │ │ # Transformers appears to handle KeyboardInterrupt (or BaseException) │ │ 750 │ │ # internally in some places, which can re-raise a different error in the handler │ │ │ │ /home/dagb/gits/heretic/src/heretic/main.py:322 in run │ │ │ │ 319 │ print() │ │ 320 │ print("Calculating per-layer refusal directions...") │ │ 321 │ print("* Obtaining residuals for good prompts...") │ │ ❱ 322 │ good_residuals = model.get_residuals_batched(good_prompts) │ │ 323 │ print("* Obtaining residuals for bad prompts...") │ │ 324 │ bad_residuals = model.get_residuals_batched(bad_prompts) │ │ 325 │ refusal_directions = F.normalize( │ │ │ │ /home/dagb/gits/heretic/src/heretic/model.py:566 in get_residuals_batched │ │ │ │ 563 │ │ residuals = [] │ │ 564 │ │ │ │ 565 │ │ for batch in batchify(prompts, self.settings.batch_size): │ │ ❱ 566 │ │ │ residuals.append(self.get_residuals(batch)) │ │ 567 │ │ │ │ 568 │ │ return torch.cat(residuals, dim=0) │ │ 569 │ │ │ │ /home/dagb/gits/heretic/src/heretic/model.py:534 in get_residuals │ │ │ │ 531 │ def get_residuals(self, prompts: list[str]) -> Tensor: │ │ 532 │ │ # We only generate one token, and we return the residual vectors │ │ 533 │ │ # at that token position, for each prompt and layer. │ │ ❱ 534 │ │ _, outputs = self.generate( │ │ 535 │ │ │ prompts, │ │ 536 │ │ │ max_new_tokens=1, │ │ 537 │ │ │ output_hidden_states=True, │ │ │ │ /home/dagb/gits/heretic/src/heretic/model.py:500 in generate │ │ │ │ 497 │ │ │ │ 498 │ │ # FIXME: The type checker has been disabled here because of the extremely comple │ │ 499 │ │ # interplay between different generate() signatures and dynamic delegatio │ │ ❱ 500 │ │ outputs = self.model.generate( │ │ 501 │ │ │ **inputs, │ │ 502 │ │ │ **kwargs, │ │ 503 │ │ │ pad_token_id=self.tokenizer.pad_token_id, │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/peft/peft_model.py:2048 in generate │ │ │ │ 2045 │ │ │ │ kwargs = get_alora_offsets_for_generate(self, *args, **kwargs) │ │ 2046 │ │ │ │ with self._enable_peft_forward_hooks(*args, **kwargs): │ │ 2047 │ │ │ │ │ kwargs = {k: v for k, v in kwargs.items() if k not in self.special_p │ │ ❱ 2048 │ │ │ │ │ outputs = self.base_model.generate(*args, **kwargs) │ │ 2049 │ │ │ else: │ │ 2050 │ │ │ │ outputs = self.base_model.generate(**kwargs) │ │ 2051 │ │ except: │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/utils/_contextlib.py:120 in │ │ decorate_context │ │ │ │ 117 │ @functools.wraps(func) │ │ 118 │ def decorate_context(*args, **kwargs): │ │ 119 │ │ with ctx_factory(): │ │ ❱ 120 │ │ │ return func(*args, **kwargs) │ │ 121 │ │ │ 122 │ return decorate_context │ │ 123 │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/generation/utils.py:2564 │ │ in generate │ │ │ │ 2561 │ │ model_kwargs["use_cache"] = generation_config.use_cache │ │ 2562 │ │ │ │ 2563 │ │ # 9. Call generation mode │ │ ❱ 2564 │ │ result = decoding_method( │ │ 2565 │ │ │ self, │ │ 2566 │ │ │ input_ids, │ │ 2567 │ │ │ logits_processor=prepared_logits_processor, │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/generation/utils.py:2784 │ │ in _sample │ │ │ │ 2781 │ │ │ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs) │ │ 2782 │ │ │ │ │ 2783 │ │ │ if is_prefill: │ │ ❱ 2784 │ │ │ │ outputs = self(**model_inputs, return_dict=True) │ │ 2785 │ │ │ │ is_prefill = False │ │ 2786 │ │ │ else: │ │ 2787 │ │ │ │ outputs = model_forward(**model_inputs, return_dict=True) │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1775 in │ │ _wrapped_call_impl │ │ │ │ 1772 │ │ if self._compiled_call_impl is not None: │ │ 1773 │ │ │ return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc] │ │ 1774 │ │ else: │ │ ❱ 1775 │ │ │ return self._call_impl(*args, **kwargs) │ │ 1776 │ │ │ 1777 │ # torchrec tests the code consistency with the following code │ │ 1778 │ # fmt: off │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1786 in │ │ _call_impl │ │ │ │ 1783 │ │ if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks │ │ 1784 │ │ │ │ or _global_backward_pre_hooks or _global_backward_hooks │ │ 1785 │ │ │ │ or _global_forward_hooks or _global_forward_pre_hooks): │ │ ❱ 1786 │ │ │ return forward_call(*args, **kwargs) │ │ 1787 │ │ │ │ 1788 │ │ result = None │ │ 1789 │ │ called_always_called_hooks = set() │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/accelerate/hooks.py:175 in │ │ new_forward │ │ │ │ 172 │ │ │ with torch.no_grad(): │ │ 173 │ │ │ │ output = module._old_forward(*args, **kwargs) │ │ 174 │ │ else: │ │ ❱ 175 │ │ │ output = module._old_forward(*args, **kwargs) │ │ 176 │ │ return module._hf_hook.post_forward(module, output) │ │ 177 │ │ │ 178 │ # Overriding a GraphModuleImpl forward freezes the forward call and later modificati │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/utils/generic.py:918 in │ │ wrapper │ │ │ │ 915 │ │ return_dict_passed = kwargs.pop("return_dict", return_dict) │ │ 916 │ │ if return_dict_passed is not None: │ │ 917 │ │ │ return_dict = return_dict_passed │ │ ❱ 918 │ │ output = func(self, *args, **kwargs) │ │ 919 │ │ if not return_dict and not isinstance(output, tuple): │ │ 920 │ │ │ output = output.to_tuple() │ │ 921 │ │ return output │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/modeling_ │ │ gpt_oss.py:668 in forward │ │ │ │ 665 │ │ ) │ │ 666 │ │ │ │ 667 │ │ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) │ │ ❱ 668 │ │ outputs: MoeModelOutputWithPast = self.model( │ │ 669 │ │ │ input_ids=input_ids, │ │ 670 │ │ │ attention_mask=attention_mask, │ │ 671 │ │ │ position_ids=position_ids, │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1775 in │ │ _wrapped_call_impl │ │ │ │ 1772 │ │ if self._compiled_call_impl is not None: │ │ 1773 │ │ │ return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc] │ │ 1774 │ │ else: │ │ ❱ 1775 │ │ │ return self._call_impl(*args, **kwargs) │ │ 1776 │ │ │ 1777 │ # torchrec tests the code consistency with the following code │ │ 1778 │ # fmt: off │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1786 in │ │ _call_impl │ │ │ │ 1783 │ │ if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks │ │ 1784 │ │ │ │ or _global_backward_pre_hooks or _global_backward_hooks │ │ 1785 │ │ │ │ or _global_forward_hooks or _global_forward_pre_hooks): │ │ ❱ 1786 │ │ │ return forward_call(*args, **kwargs) │ │ 1787 │ │ │ │ 1788 │ │ result = None │ │ 1789 │ │ called_always_called_hooks = set() │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/utils/generic.py:1072 in │ │ wrapper │ │ │ │ 1069 │ │ │ │ │ │ │ monkey_patched_layers.append((module, original_forward)) │ │ 1070 │ │ │ │ │ 1071 │ │ │ try: │ │ ❱ 1072 │ │ │ │ outputs = func(self, *args, **kwargs) │ │ 1073 │ │ │ except TypeError as original_exception: │ │ 1074 │ │ │ │ # If we get a TypeError, it's possible that the model is not receiving t │ │ 1075 │ │ │ │ # Get a TypeError even after removing the recordable kwargs -> re-raise │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/modeling_ │ │ gpt_oss.py:507 in forward │ │ │ │ 504 │ │ position_embeddings = self.rotary_emb(hidden_states, position_ids) │ │ 505 │ │ │ │ 506 │ │ for decoder_layer in self.layers: │ │ ❱ 507 │ │ │ hidden_states = decoder_layer( │ │ 508 │ │ │ │ hidden_states, │ │ 509 │ │ │ │ attention_mask=causal_mask_mapping[decoder_layer.attention_type], │ │ 510 │ │ │ │ position_ids=position_ids, │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/modeling_layers.py:94 in │ │ __call__ │ │ │ │ 91 │ │ │ │ logger.warning_once(message) │ │ 92 │ │ │ │ │ 93 │ │ │ return self._gradient_checkpointing_func(partial(super().__call__, **kwargs) │ │ ❱ 94 │ │ return super().__call__(*args, **kwargs) │ │ 95 │ │ 96 │ │ 97 @auto_docstring │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1775 in │ │ _wrapped_call_impl │ │ │ │ 1772 │ │ if self._compiled_call_impl is not None: │ │ 1773 │ │ │ return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc] │ │ 1774 │ │ else: │ │ ❱ 1775 │ │ │ return self._call_impl(*args, **kwargs) │ │ 1776 │ │ │ 1777 │ # torchrec tests the code consistency with the following code │ │ 1778 │ # fmt: off │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1786 in │ │ _call_impl │ │ │ │ 1783 │ │ if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks │ │ 1784 │ │ │ │ or _global_backward_pre_hooks or _global_backward_hooks │ │ 1785 │ │ │ │ or _global_forward_hooks or _global_forward_pre_hooks): │ │ ❱ 1786 │ │ │ return forward_call(*args, **kwargs) │ │ 1787 │ │ │ │ 1788 │ │ result = None │ │ 1789 │ │ called_always_called_hooks = set() │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/utils/generic.py:1031 in │ │ wrapped_forward │ │ │ │ 1028 │ │ │ │ │ │ ): │ │ 1029 │ │ │ │ │ │ │ output = orig_forward(*args, **kwargs) │ │ 1030 │ │ │ │ │ else: │ │ ❱ 1031 │ │ │ │ │ │ output = orig_forward(*args, **kwargs) │ │ 1032 │ │ │ │ │ if not isinstance(output, tuple): │ │ 1033 │ │ │ │ │ │ collected_outputs[key] += (output,) │ │ 1034 │ │ │ │ │ elif output[index] is not None: │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/accelerate/hooks.py:175 in │ │ new_forward │ │ │ │ 172 │ │ │ with torch.no_grad(): │ │ 173 │ │ │ │ output = module._old_forward(*args, **kwargs) │ │ 174 │ │ else: │ │ ❱ 175 │ │ │ output = module._old_forward(*args, **kwargs) │ │ 176 │ │ return module._hf_hook.post_forward(module, output) │ │ 177 │ │ │ 178 │ # Overriding a GraphModuleImpl forward freezes the forward call and later modificati │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/utils/deprecation.py:172 │ │ in wrapped_func │ │ │ │ 169 │ │ │ │ # DeprecationWarning is ignored by default, so we use FutureWarning inst │ │ 170 │ │ │ │ warnings.warn(message, FutureWarning, stacklevel=2) │ │ 171 │ │ │ │ │ ❱ 172 │ │ │ return func(*args, **kwargs) │ │ 173 │ │ │ │ 174 │ │ return wrapped_func │ │ 175 │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/modeling_ │ │ gpt_oss.py:386 in forward │ │ │ │ 383 │ │ # Fully Connected │ │ 384 │ │ residual = hidden_states │ │ 385 │ │ hidden_states = self.post_attention_layernorm(hidden_states) │ │ ❱ 386 │ │ hidden_states, _ = self.mlp(hidden_states) # diff with llama: router scores │ │ 387 │ │ hidden_states = residual + hidden_states │ │ 388 │ │ return hidden_states │ │ 389 │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1775 in │ │ _wrapped_call_impl │ │ │ │ 1772 │ │ if self._compiled_call_impl is not None: │ │ 1773 │ │ │ return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc] │ │ 1774 │ │ else: │ │ ❱ 1775 │ │ │ return self._call_impl(*args, **kwargs) │ │ 1776 │ │ │ 1777 │ # torchrec tests the code consistency with the following code │ │ 1778 │ # fmt: off │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1786 in │ │ _call_impl │ │ │ │ 1783 │ │ if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks │ │ 1784 │ │ │ │ or _global_backward_pre_hooks or _global_backward_hooks │ │ 1785 │ │ │ │ or _global_forward_hooks or _global_forward_pre_hooks): │ │ ❱ 1786 │ │ │ return forward_call(*args, **kwargs) │ │ 1787 │ │ │ │ 1788 │ │ result = None │ │ 1789 │ │ called_always_called_hooks = set() │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/accelerate/hooks.py:175 in │ │ new_forward │ │ │ │ 172 │ │ │ with torch.no_grad(): │ │ 173 │ │ │ │ output = module._old_forward(*args, **kwargs) │ │ 174 │ │ else: │ │ ❱ 175 │ │ │ output = module._old_forward(*args, **kwargs) │ │ 176 │ │ return module._hf_hook.post_forward(module, output) │ │ 177 │ │ │ 178 │ # Overriding a GraphModuleImpl forward freezes the forward call and later modificati │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/modeling_ │ │ gpt_oss.py:170 in forward │ │ │ │ 167 │ │ │ 168 │ def forward(self, hidden_states): │ │ 169 │ │ router_scores, router_indices = self.router(hidden_states) # (num_experts, seq_ │ │ ❱ 170 │ │ routed_out = self.experts(hidden_states, router_indices=router_indices, routing_ │ │ 171 │ │ return routed_out, router_scores │ │ 172 │ │ 173 │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1775 in │ │ _wrapped_call_impl │ │ │ │ 1772 │ │ if self._compiled_call_impl is not None: │ │ 1773 │ │ │ return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc] │ │ 1774 │ │ else: │ │ ❱ 1775 │ │ │ return self._call_impl(*args, **kwargs) │ │ 1776 │ │ │ 1777 │ # torchrec tests the code consistency with the following code │ │ 1778 │ # fmt: off │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/torch/nn/modules/module.py:1786 in │ │ _call_impl │ │ │ │ 1783 │ │ if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks │ │ 1784 │ │ │ │ or _global_backward_pre_hooks or _global_backward_hooks │ │ 1785 │ │ │ │ or _global_forward_hooks or _global_forward_pre_hooks): │ │ ❱ 1786 │ │ │ return forward_call(*args, **kwargs) │ │ 1787 │ │ │ │ 1788 │ │ result = None │ │ 1789 │ │ called_always_called_hooks = set() │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/accelerate/hooks.py:175 in │ │ new_forward │ │ │ │ 172 │ │ │ with torch.no_grad(): │ │ 173 │ │ │ │ output = module._old_forward(*args, **kwargs) │ │ 174 │ │ else: │ │ ❱ 175 │ │ │ output = module._old_forward(*args, **kwargs) │ │ 176 │ │ return module._hf_hook.post_forward(module, output) │ │ 177 │ │ │ 178 │ # Overriding a GraphModuleImpl forward freezes the forward call and later modificati │ │ │ │ /home/dagb/gits/heretic/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/modeling_ │ │ gpt_oss.py:130 in forward │ │ │ │ 127 │ │ else: │ │ 128 │ │ │ hidden_states = hidden_states.repeat(num_experts, 1) │ │ 129 │ │ │ hidden_states = hidden_states.view(num_experts, -1, self.hidden_size) │ │ ❱ 130 │ │ │ gate_up = torch.bmm(hidden_states, self.gate_up_proj) + self.gate_up_proj_bi │ │ 131 │ │ │ gate, up = gate_up[..., ::2], gate_up[..., 1::2] │ │ 132 │ │ │ gate = gate.clamp(min=None, max=self.limit) │ │ 133 │ │ │ up = up.clamp(min=-self.limit, max=self.limit) │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯ OutOfMemoryError: CUDA out of memory. Tried to allocate 2.84 GiB. GPU 0 has a total capacity of 23.55 GiB of which 1.95 GiB is free. Including non-PyTorch memory, this process has 21.59 GiB memory in use. Of the allocated memory 13.38 GiB is allocated by PyTorch, and 7.89 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables) (heretic) dagb@p53 ~/gits/heretic $ ``` 386 powers through: ``` .... Calculating per-layer refusal directions... * Obtaining residuals for good prompts... * Obtaining residuals for bad prompts... Running trial 1 of 200... * Parameters: * direction_index = per layer * attn.o_proj.max_weight = 1.39 * attn.o_proj.max_weight_position = 20.98 * .... ```
Author
Owner

@dagbdagb commented on GitHub (Dec 28, 2025):

383 is necessary to elliminate my 6GB onboard RTX 3000 from being utilized.

<!-- gh-comment-id:3694908608 --> @dagbdagb commented on GitHub (Dec 28, 2025): 383 is necessary to elliminate my 6GB onboard RTX 3000 from being utilized.
Author
Owner

@dagbdagb commented on GitHub (Dec 28, 2025):

I still see:

* Trying batch size 64... 
Ok (393 tokens/s)
* Trying batch size 128... Failed (CUDA out of memory. Tried to allocate 2.64 GiB. GPU 0 has a total capacity of 23.55 GiB of which 
668.00 MiB is free. Including non-PyTorch memory, this process has 22.89 GiB memory in use. Of the 
allocated memory 22.45 GiB is allocated by PyTorch, and 126.81 MiB is reserved by PyTorch but 
unallocated. If reserved but unallocated memory is large try setting 
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation.  See documentation for Memory 
Management  (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables))
* Chosen batch size: 64

... on the last run. But heretic does not die later, as in the first run.

The installed pytorch version is 2.9.0.

heretic at cf8cf6f349 (Dec 22)

<!-- gh-comment-id:3694912498 --> @dagbdagb commented on GitHub (Dec 28, 2025): I still see: ``` * Trying batch size 64... Ok (393 tokens/s) * Trying batch size 128... Failed (CUDA out of memory. Tried to allocate 2.64 GiB. GPU 0 has a total capacity of 23.55 GiB of which 668.00 MiB is free. Including non-PyTorch memory, this process has 22.89 GiB memory in use. Of the allocated memory 22.45 GiB is allocated by PyTorch, and 126.81 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)) * Chosen batch size: 64 ``` ... on the last run. But heretic does not die later, as in the first run. The installed pytorch version is 2.9.0. heretic at cf8cf6f3496e4079fcbb4f24d9893247204f7e24 (Dec 22)
Author
Owner

@p-e-w commented on GitHub (Dec 29, 2025):

Do you maybe have that variable in your global environment already, preventing Heretic from setting it?

<!-- gh-comment-id:3696562828 --> @p-e-w commented on GitHub (Dec 29, 2025): Do you maybe have that variable in your global environment already, preventing Heretic from setting it?
Author
Owner

@dagbdagb commented on GitHub (Dec 29, 2025):

Fair question. No.

Last login: Mon Dec 29 13:47:46 -00 2025 from 192.168.100.23 on pts/5
dagb@p53 ~ $ cd gits/heretic/
dagb@p53 ~/gits/heretic $ . .venv/bin/activate
(heretic) dagb@p53 ~/gits/heretic $ env | egrep "PY|CU"
(heretic) dagb@p53 ~/gits/heretic $ 
<!-- gh-comment-id:3696588964 --> @dagbdagb commented on GitHub (Dec 29, 2025): Fair question. No. ``` Last login: Mon Dec 29 13:47:46 -00 2025 from 192.168.100.23 on pts/5 dagb@p53 ~ $ cd gits/heretic/ dagb@p53 ~/gits/heretic $ . .venv/bin/activate (heretic) dagb@p53 ~/gits/heretic $ env | egrep "PY|CU" (heretic) dagb@p53 ~/gits/heretic $ ```
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
p-e-w/heretic#43
No description provided.