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 #18] Qwen3 32b VL support? #8

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

Originally created by @phr00t on GitHub (Nov 18, 2025).
Original GitHub issue: https://github.com/p-e-w/heretic/issues/18

Perhaps related to https://github.com/p-e-w/heretic/pull/11 ?

torch-2.9.1+cu130

Name: transformers
Version: 4.57.1

`phr00t@AI-BOT /cygdrive/d/Heretic
$ heretic Qwen/Qwen3-VL-32B-Instruct
█░█░█▀▀░█▀▄░█▀▀░▀█▀░█░█▀▀ v1.0.1
█▀█░█▀▀░█▀▄░█▀▀░░█░░█░█░░
▀░▀░▀▀▀░▀░▀░▀▀▀░░▀░░▀░▀▀▀ https://github.com/p-e-w/heretic

GPU type: NVIDIA GeForce RTX 5070 Ti

Loading model Qwen/Qwen3-VL-32B-Instruct...
tokenizer_config.json: 10.9kB [00:00, ?B/s]
C:\Users\phr00t\AppData\Roaming\Python\Python312\site-packages\huggingface_hub\file_download.py:143: UserWarning: huggingface_hub cache-system uses symlinks by default to efficiently store duplicated files but your machine does not support them in C:\Users\phr00t.cache\huggingface\hub\models--Qwen--Qwen3-VL-32B-Instruct. Caching files will still work but in a degraded version that might require more space on your disk. This warning can be disabled by setting the HF_HUB_DISABLE_SYMLINKS_WARNING environment variable. For more details, see https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations.
To support symlinks on Windows, you either need to activate Developer Mode or to run Python as an administrator. In order to activate developer mode, see this article: https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development
warnings.warn(message)
vocab.json: 2.78MB [00:00, 11.4MB/s]
merges.txt: 1.67MB [00:00, 12.2MB/s]
tokenizer.json: 7.03MB [00:00, 18.9MB/s]
config.json: 1.47kB [00:00, ?B/s]
Failed (Unrecognized configuration class <class 'transformers.models.qwen3_vl.configuration_qwen3_vl.Qwen3VLConfig'> for this
kind of AutoModel: AutoModelForCausalLM.
Model type should be one of ApertusConfig, ArceeConfig, AriaTextConfig, BambaConfig, BartConfig, BertConfig,
BertGenerationConfig, BigBirdConfig, BigBirdPegasusConfig, BioGptConfig, BitNetConfig, BlenderbotConfig, BlenderbotSmallConfig,
BloomConfig, BltConfig, CamembertConfig, LlamaConfig, CodeGenConfig, CohereConfig, Cohere2Config, CpmAntConfig, CTRLConfig,
Data2VecTextConfig, DbrxConfig, DeepseekV2Config, DeepseekV3Config, DiffLlamaConfig, DogeConfig, Dots1Config, ElectraConfig,
Emu3Config, ErnieConfig, Ernie4_5Config, Ernie4_5_MoeConfig, Exaone4Config, FalconConfig, FalconH1Config, FalconMambaConfig,
FlexOlmoConfig, FuyuConfig, GemmaConfig, Gemma2Config, Gemma3Config, Gemma3TextConfig, Gemma3nConfig, Gemma3nTextConfig,
GitConfig, GlmConfig, Glm4Config, Glm4MoeConfig, GotOcr2Config, GPT2Config, GPT2Config, GPTBigCodeConfig, GPTNeoConfig,
GPTNeoXConfig, GPTNeoXJapaneseConfig, GptOssConfig, GPTJConfig, GraniteConfig, GraniteMoeConfig, GraniteMoeHybridConfig,
GraniteMoeSharedConfig, HeliumConfig, HunYuanDenseV1Config, HunYuanMoEV1Config, JambaConfig, JetMoeConfig, Lfm2Config,
LlamaConfig, Llama4Config, Llama4TextConfig, LongcatFlashConfig, MambaConfig, Mamba2Config, MarianConfig, MBartConfig,
MegaConfig, MegatronBertConfig, MiniMaxConfig, MinistralConfig, MistralConfig, MixtralConfig, MllamaConfig,
ModernBertDecoderConfig, MoshiConfig, MptConfig, MusicgenConfig, MusicgenMelodyConfig, MvpConfig, NemotronConfig, OlmoConfig,
Olmo2Config, Olmo3Config, OlmoeConfig, OpenLlamaConfig, OpenAIGPTConfig, OPTConfig, PegasusConfig, PersimmonConfig, PhiConfig,
Phi3Config, Phi4MultimodalConfig, PhimoeConfig, PLBartConfig, ProphetNetConfig, QDQBertConfig, Qwen2Config, Qwen2MoeConfig,
Qwen3Config, Qwen3MoeConfig, Qwen3NextConfig, RecurrentGemmaConfig, ReformerConfig, RemBertConfig, RobertaConfig,
RobertaPreLayerNormConfig, RoCBertConfig, RoFormerConfig, RwkvConfig, SeedOssConfig, SmolLM3Config, Speech2Text2Config,
StableLmConfig, Starcoder2Config, TransfoXLConfig, TrOCRConfig, VaultGemmaConfig, WhisperConfig, XGLMConfig, XLMConfig,
XLMProphetNetConfig, XLMRobertaConfig, XLMRobertaXLConfig, XLNetConfig, xLSTMConfig, XmodConfig, ZambaConfig, Zamba2Config.)

  • Trying dtype float16... Failed (Unrecognized configuration class <class 'transformers.models.qwen3_vl.configuration_qwen3_vl.Qwen3VLConfig'> for this
    kind of AutoModel: AutoModelForCausalLM.
    Model type should be one of ApertusConfig, ArceeConfig, AriaTextConfig, BambaConfig, BartConfig, BertConfig,
    BertGenerationConfig, BigBirdConfig, BigBirdPegasusConfig, BioGptConfig, BitNetConfig, BlenderbotConfig, BlenderbotSmallConfig,
    BloomConfig, BltConfig, CamembertConfig, LlamaConfig, CodeGenConfig, CohereConfig, Cohere2Config, CpmAntConfig, CTRLConfig,
    Data2VecTextConfig, DbrxConfig, DeepseekV2Config, DeepseekV3Config, DiffLlamaConfig, DogeConfig, Dots1Config, ElectraConfig,
    Emu3Config, ErnieConfig, Ernie4_5Config, Ernie4_5_MoeConfig, Exaone4Config, FalconConfig, FalconH1Config, FalconMambaConfig,
    FlexOlmoConfig, FuyuConfig, GemmaConfig, Gemma2Config, Gemma3Config, Gemma3TextConfig, Gemma3nConfig, Gemma3nTextConfig,
    GitConfig, GlmConfig, Glm4Config, Glm4MoeConfig, GotOcr2Config, GPT2Config, GPT2Config, GPTBigCodeConfig, GPTNeoConfig,
    GPTNeoXConfig, GPTNeoXJapaneseConfig, GptOssConfig, GPTJConfig, GraniteConfig, GraniteMoeConfig, GraniteMoeHybridConfig,
    GraniteMoeSharedConfig, HeliumConfig, HunYuanDenseV1Config, HunYuanMoEV1Config, JambaConfig, JetMoeConfig, Lfm2Config,
    LlamaConfig, Llama4Config, Llama4TextConfig, LongcatFlashConfig, MambaConfig, Mamba2Config, MarianConfig, MBartConfig,
    MegaConfig, MegatronBertConfig, MiniMaxConfig, MinistralConfig, MistralConfig, MixtralConfig, MllamaConfig,
    ModernBertDecoderConfig, MoshiConfig, MptConfig, MusicgenConfig, MusicgenMelodyConfig, MvpConfig, NemotronConfig, OlmoConfig,
    Olmo2Config, Olmo3Config, OlmoeConfig, OpenLlamaConfig, OpenAIGPTConfig, OPTConfig, PegasusConfig, PersimmonConfig, PhiConfig,
    Phi3Config, Phi4MultimodalConfig, PhimoeConfig, PLBartConfig, ProphetNetConfig, QDQBertConfig, Qwen2Config, Qwen2MoeConfig,
    Qwen3Config, Qwen3MoeConfig, Qwen3NextConfig, RecurrentGemmaConfig, ReformerConfig, RemBertConfig, RobertaConfig,
    RobertaPreLayerNormConfig, RoCBertConfig, RoFormerConfig, RwkvConfig, SeedOssConfig, SmolLM3Config, Speech2Text2Config,
    StableLmConfig, Starcoder2Config, TransfoXLConfig, TrOCRConfig, VaultGemmaConfig, WhisperConfig, XGLMConfig, XLMConfig,
    XLMProphetNetConfig, XLMRobertaConfig, XLMRobertaXLConfig, XLNetConfig, xLSTMConfig, XmodConfig, ZambaConfig, Zamba2Config.)
  • Trying dtype float32... Failed (Unrecognized configuration class <class 'transformers.models.qwen3_vl.configuration_qwen3_vl.Qwen3VLConfig'> for this
    kind of AutoModel: AutoModelForCausalLM.
    Model type should be one of ApertusConfig, ArceeConfig, AriaTextConfig, BambaConfig, BartConfig, BertConfig,
    BertGenerationConfig, BigBirdConfig, BigBirdPegasusConfig, BioGptConfig, BitNetConfig, BlenderbotConfig, BlenderbotSmallConfig,
    BloomConfig, BltConfig, CamembertConfig, LlamaConfig, CodeGenConfig, CohereConfig, Cohere2Config, CpmAntConfig, CTRLConfig,
    Data2VecTextConfig, DbrxConfig, DeepseekV2Config, DeepseekV3Config, DiffLlamaConfig, DogeConfig, Dots1Config, ElectraConfig,
    Emu3Config, ErnieConfig, Ernie4_5Config, Ernie4_5_MoeConfig, Exaone4Config, FalconConfig, FalconH1Config, FalconMambaConfig,
    FlexOlmoConfig, FuyuConfig, GemmaConfig, Gemma2Config, Gemma3Config, Gemma3TextConfig, Gemma3nConfig, Gemma3nTextConfig,
    GitConfig, GlmConfig, Glm4Config, Glm4MoeConfig, GotOcr2Config, GPT2Config, GPT2Config, GPTBigCodeConfig, GPTNeoConfig,
    GPTNeoXConfig, GPTNeoXJapaneseConfig, GptOssConfig, GPTJConfig, GraniteConfig, GraniteMoeConfig, GraniteMoeHybridConfig,
    GraniteMoeSharedConfig, HeliumConfig, HunYuanDenseV1Config, HunYuanMoEV1Config, JambaConfig, JetMoeConfig, Lfm2Config,
    LlamaConfig, Llama4Config, Llama4TextConfig, LongcatFlashConfig, MambaConfig, Mamba2Config, MarianConfig, MBartConfig,
    MegaConfig, MegatronBertConfig, MiniMaxConfig, MinistralConfig, MistralConfig, MixtralConfig, MllamaConfig,
    ModernBertDecoderConfig, MoshiConfig, MptConfig, MusicgenConfig, MusicgenMelodyConfig, MvpConfig, NemotronConfig, OlmoConfig,
    Olmo2Config, Olmo3Config, OlmoeConfig, OpenLlamaConfig, OpenAIGPTConfig, OPTConfig, PegasusConfig, PersimmonConfig, PhiConfig,
    Phi3Config, Phi4MultimodalConfig, PhimoeConfig, PLBartConfig, ProphetNetConfig, QDQBertConfig, Qwen2Config, Qwen2MoeConfig,
    Qwen3Config, Qwen3MoeConfig, Qwen3NextConfig, RecurrentGemmaConfig, ReformerConfig, RemBertConfig, RobertaConfig,
    RobertaPreLayerNormConfig, RoCBertConfig, RoFormerConfig, RwkvConfig, SeedOssConfig, SmolLM3Config, Speech2Text2Config,
    StableLmConfig, Starcoder2Config, TransfoXLConfig, TrOCRConfig, VaultGemmaConfig, WhisperConfig, XGLMConfig, XLMConfig,
    XLMProphetNetConfig, XLMRobertaConfig, XLMRobertaXLConfig, XLNetConfig, xLSTMConfig, XmodConfig, ZambaConfig, Zamba2Config.)
    ╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮
    │ in _run_module_as_main:198 │
    │ in _run_code:88 │
    │ │
    │ in :7 │
    │ │
    │ 4 from heretic.main import main │
    │ 5 if name == 'main': │
    │ 6 │ sys.argv[0] = re.sub(r'(-script.pyw|.exe)?$', '', sys.argv[0]) │
    │ ❱ 7 │ sys.exit(main()) │
    │ 8 │
    │ │
    │ C:\Users\phr00t\AppData\Roaming\Python\Python312\site-packages\heretic\main.py:506 in main │
    │ │
    │ 503 │ install() │
    │ 504 │ │
    │ 505 │ try: │
    │ ❱ 506 │ │ run() │
    │ 507 │ except BaseException as error: │
    │ 508 │ │ # Transformers appears to handle KeyboardInterrupt (or BaseException) │
    │ 509 │ │ # internally in some places, which can re-raise a different error in the handler │
    │ │
    │ C:\Users\phr00t\AppData\Roaming\Python\Python312\site-packages\heretic\main.py:116 in run │
    │ │
    │ 113 │ # Silence the warning about multivariate TPE being experimental. │
    │ 114 │ warnings.filterwarnings("ignore", category=ExperimentalWarning) │
    │ 115 │ │
    │ ❱ 116 │ model = Model(settings) │
    │ 117 │ │
    │ 118 │ print() │
    │ 119 │ print(f"Loading good prompts from [bold]{settings.good_prompts.dataset}[/]...") │
    │ │
    │ C:\Users\phr00t\AppData\Roaming\Python\Python312\site-packages\heretic\model.py:76 in init │
    │ │
    │ 73 │ │ │ break │
    │ 74 │ │ │
    │ 75 │ │ if self.model is None: │
    │ ❱ 76 │ │ │ raise Exception("Failed to load model with all configured dtypes.") │
    │ 77 │ │ │
    │ 78 │ │ print(f"* Transformer model with [bold]{len(self.get_layers())}[/] layers") │
    │ 79 │ │ print("* Abliterable components:") │
    ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
    Exception: Failed to load model with all configured dtypes.`
Originally created by @phr00t on GitHub (Nov 18, 2025). Original GitHub issue: https://github.com/p-e-w/heretic/issues/18 Perhaps related to https://github.com/p-e-w/heretic/pull/11 ? torch-2.9.1+cu130 Name: transformers Version: 4.57.1 `phr00t@AI-BOT /cygdrive/d/Heretic $ heretic Qwen/Qwen3-VL-32B-Instruct █░█░█▀▀░█▀▄░█▀▀░▀█▀░█░█▀▀ v1.0.1 █▀█░█▀▀░█▀▄░█▀▀░░█░░█░█░░ ▀░▀░▀▀▀░▀░▀░▀▀▀░░▀░░▀░▀▀▀ https://github.com/p-e-w/heretic GPU type: NVIDIA GeForce RTX 5070 Ti Loading model Qwen/Qwen3-VL-32B-Instruct... tokenizer_config.json: 10.9kB [00:00, ?B/s] C:\Users\phr00t\AppData\Roaming\Python\Python312\site-packages\huggingface_hub\file_download.py:143: UserWarning: `huggingface_hub` cache-system uses symlinks by default to efficiently store duplicated files but your machine does not support them in C:\Users\phr00t\.cache\huggingface\hub\models--Qwen--Qwen3-VL-32B-Instruct. Caching files will still work but in a degraded version that might require more space on your disk. This warning can be disabled by setting the `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For more details, see https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations. To support symlinks on Windows, you either need to activate Developer Mode or to run Python as an administrator. In order to activate developer mode, see this article: https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development warnings.warn(message) vocab.json: 2.78MB [00:00, 11.4MB/s] merges.txt: 1.67MB [00:00, 12.2MB/s] tokenizer.json: 7.03MB [00:00, 18.9MB/s] config.json: 1.47kB [00:00, ?B/s] Failed (Unrecognized configuration class <class 'transformers.models.qwen3_vl.configuration_qwen3_vl.Qwen3VLConfig'> for this kind of AutoModel: AutoModelForCausalLM. Model type should be one of ApertusConfig, ArceeConfig, AriaTextConfig, BambaConfig, BartConfig, BertConfig, BertGenerationConfig, BigBirdConfig, BigBirdPegasusConfig, BioGptConfig, BitNetConfig, BlenderbotConfig, BlenderbotSmallConfig, BloomConfig, BltConfig, CamembertConfig, LlamaConfig, CodeGenConfig, CohereConfig, Cohere2Config, CpmAntConfig, CTRLConfig, Data2VecTextConfig, DbrxConfig, DeepseekV2Config, DeepseekV3Config, DiffLlamaConfig, DogeConfig, Dots1Config, ElectraConfig, Emu3Config, ErnieConfig, Ernie4_5Config, Ernie4_5_MoeConfig, Exaone4Config, FalconConfig, FalconH1Config, FalconMambaConfig, FlexOlmoConfig, FuyuConfig, GemmaConfig, Gemma2Config, Gemma3Config, Gemma3TextConfig, Gemma3nConfig, Gemma3nTextConfig, GitConfig, GlmConfig, Glm4Config, Glm4MoeConfig, GotOcr2Config, GPT2Config, GPT2Config, GPTBigCodeConfig, GPTNeoConfig, GPTNeoXConfig, GPTNeoXJapaneseConfig, GptOssConfig, GPTJConfig, GraniteConfig, GraniteMoeConfig, GraniteMoeHybridConfig, GraniteMoeSharedConfig, HeliumConfig, HunYuanDenseV1Config, HunYuanMoEV1Config, JambaConfig, JetMoeConfig, Lfm2Config, LlamaConfig, Llama4Config, Llama4TextConfig, LongcatFlashConfig, MambaConfig, Mamba2Config, MarianConfig, MBartConfig, MegaConfig, MegatronBertConfig, MiniMaxConfig, MinistralConfig, MistralConfig, MixtralConfig, MllamaConfig, ModernBertDecoderConfig, MoshiConfig, MptConfig, MusicgenConfig, MusicgenMelodyConfig, MvpConfig, NemotronConfig, OlmoConfig, Olmo2Config, Olmo3Config, OlmoeConfig, OpenLlamaConfig, OpenAIGPTConfig, OPTConfig, PegasusConfig, PersimmonConfig, PhiConfig, Phi3Config, Phi4MultimodalConfig, PhimoeConfig, PLBartConfig, ProphetNetConfig, QDQBertConfig, Qwen2Config, Qwen2MoeConfig, Qwen3Config, Qwen3MoeConfig, Qwen3NextConfig, RecurrentGemmaConfig, ReformerConfig, RemBertConfig, RobertaConfig, RobertaPreLayerNormConfig, RoCBertConfig, RoFormerConfig, RwkvConfig, SeedOssConfig, SmolLM3Config, Speech2Text2Config, StableLmConfig, Starcoder2Config, TransfoXLConfig, TrOCRConfig, VaultGemmaConfig, WhisperConfig, XGLMConfig, XLMConfig, XLMProphetNetConfig, XLMRobertaConfig, XLMRobertaXLConfig, XLNetConfig, xLSTMConfig, XmodConfig, ZambaConfig, Zamba2Config.) * Trying dtype float16... Failed (Unrecognized configuration class <class 'transformers.models.qwen3_vl.configuration_qwen3_vl.Qwen3VLConfig'> for this kind of AutoModel: AutoModelForCausalLM. Model type should be one of ApertusConfig, ArceeConfig, AriaTextConfig, BambaConfig, BartConfig, BertConfig, BertGenerationConfig, BigBirdConfig, BigBirdPegasusConfig, BioGptConfig, BitNetConfig, BlenderbotConfig, BlenderbotSmallConfig, BloomConfig, BltConfig, CamembertConfig, LlamaConfig, CodeGenConfig, CohereConfig, Cohere2Config, CpmAntConfig, CTRLConfig, Data2VecTextConfig, DbrxConfig, DeepseekV2Config, DeepseekV3Config, DiffLlamaConfig, DogeConfig, Dots1Config, ElectraConfig, Emu3Config, ErnieConfig, Ernie4_5Config, Ernie4_5_MoeConfig, Exaone4Config, FalconConfig, FalconH1Config, FalconMambaConfig, FlexOlmoConfig, FuyuConfig, GemmaConfig, Gemma2Config, Gemma3Config, Gemma3TextConfig, Gemma3nConfig, Gemma3nTextConfig, GitConfig, GlmConfig, Glm4Config, Glm4MoeConfig, GotOcr2Config, GPT2Config, GPT2Config, GPTBigCodeConfig, GPTNeoConfig, GPTNeoXConfig, GPTNeoXJapaneseConfig, GptOssConfig, GPTJConfig, GraniteConfig, GraniteMoeConfig, GraniteMoeHybridConfig, GraniteMoeSharedConfig, HeliumConfig, HunYuanDenseV1Config, HunYuanMoEV1Config, JambaConfig, JetMoeConfig, Lfm2Config, LlamaConfig, Llama4Config, Llama4TextConfig, LongcatFlashConfig, MambaConfig, Mamba2Config, MarianConfig, MBartConfig, MegaConfig, MegatronBertConfig, MiniMaxConfig, MinistralConfig, MistralConfig, MixtralConfig, MllamaConfig, ModernBertDecoderConfig, MoshiConfig, MptConfig, MusicgenConfig, MusicgenMelodyConfig, MvpConfig, NemotronConfig, OlmoConfig, Olmo2Config, Olmo3Config, OlmoeConfig, OpenLlamaConfig, OpenAIGPTConfig, OPTConfig, PegasusConfig, PersimmonConfig, PhiConfig, Phi3Config, Phi4MultimodalConfig, PhimoeConfig, PLBartConfig, ProphetNetConfig, QDQBertConfig, Qwen2Config, Qwen2MoeConfig, Qwen3Config, Qwen3MoeConfig, Qwen3NextConfig, RecurrentGemmaConfig, ReformerConfig, RemBertConfig, RobertaConfig, RobertaPreLayerNormConfig, RoCBertConfig, RoFormerConfig, RwkvConfig, SeedOssConfig, SmolLM3Config, Speech2Text2Config, StableLmConfig, Starcoder2Config, TransfoXLConfig, TrOCRConfig, VaultGemmaConfig, WhisperConfig, XGLMConfig, XLMConfig, XLMProphetNetConfig, XLMRobertaConfig, XLMRobertaXLConfig, XLNetConfig, xLSTMConfig, XmodConfig, ZambaConfig, Zamba2Config.) * Trying dtype float32... Failed (Unrecognized configuration class <class 'transformers.models.qwen3_vl.configuration_qwen3_vl.Qwen3VLConfig'> for this kind of AutoModel: AutoModelForCausalLM. Model type should be one of ApertusConfig, ArceeConfig, AriaTextConfig, BambaConfig, BartConfig, BertConfig, BertGenerationConfig, BigBirdConfig, BigBirdPegasusConfig, BioGptConfig, BitNetConfig, BlenderbotConfig, BlenderbotSmallConfig, BloomConfig, BltConfig, CamembertConfig, LlamaConfig, CodeGenConfig, CohereConfig, Cohere2Config, CpmAntConfig, CTRLConfig, Data2VecTextConfig, DbrxConfig, DeepseekV2Config, DeepseekV3Config, DiffLlamaConfig, DogeConfig, Dots1Config, ElectraConfig, Emu3Config, ErnieConfig, Ernie4_5Config, Ernie4_5_MoeConfig, Exaone4Config, FalconConfig, FalconH1Config, FalconMambaConfig, FlexOlmoConfig, FuyuConfig, GemmaConfig, Gemma2Config, Gemma3Config, Gemma3TextConfig, Gemma3nConfig, Gemma3nTextConfig, GitConfig, GlmConfig, Glm4Config, Glm4MoeConfig, GotOcr2Config, GPT2Config, GPT2Config, GPTBigCodeConfig, GPTNeoConfig, GPTNeoXConfig, GPTNeoXJapaneseConfig, GptOssConfig, GPTJConfig, GraniteConfig, GraniteMoeConfig, GraniteMoeHybridConfig, GraniteMoeSharedConfig, HeliumConfig, HunYuanDenseV1Config, HunYuanMoEV1Config, JambaConfig, JetMoeConfig, Lfm2Config, LlamaConfig, Llama4Config, Llama4TextConfig, LongcatFlashConfig, MambaConfig, Mamba2Config, MarianConfig, MBartConfig, MegaConfig, MegatronBertConfig, MiniMaxConfig, MinistralConfig, MistralConfig, MixtralConfig, MllamaConfig, ModernBertDecoderConfig, MoshiConfig, MptConfig, MusicgenConfig, MusicgenMelodyConfig, MvpConfig, NemotronConfig, OlmoConfig, Olmo2Config, Olmo3Config, OlmoeConfig, OpenLlamaConfig, OpenAIGPTConfig, OPTConfig, PegasusConfig, PersimmonConfig, PhiConfig, Phi3Config, Phi4MultimodalConfig, PhimoeConfig, PLBartConfig, ProphetNetConfig, QDQBertConfig, Qwen2Config, Qwen2MoeConfig, Qwen3Config, Qwen3MoeConfig, Qwen3NextConfig, RecurrentGemmaConfig, ReformerConfig, RemBertConfig, RobertaConfig, RobertaPreLayerNormConfig, RoCBertConfig, RoFormerConfig, RwkvConfig, SeedOssConfig, SmolLM3Config, Speech2Text2Config, StableLmConfig, Starcoder2Config, TransfoXLConfig, TrOCRConfig, VaultGemmaConfig, WhisperConfig, XGLMConfig, XLMConfig, XLMProphetNetConfig, XLMRobertaConfig, XLMRobertaXLConfig, XLNetConfig, xLSTMConfig, XmodConfig, ZambaConfig, Zamba2Config.) ╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮ │ in _run_module_as_main:198 │ │ in _run_code:88 │ │ │ │ in <module>:7 │ │ │ │ 4 from heretic.main import main │ │ 5 if __name__ == '__main__': │ │ 6 │ sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) │ │ ❱ 7 │ sys.exit(main()) │ │ 8 │ │ │ │ C:\Users\phr00t\AppData\Roaming\Python\Python312\site-packages\heretic\main.py:506 in main │ │ │ │ 503 │ install() │ │ 504 │ │ │ 505 │ try: │ │ ❱ 506 │ │ run() │ │ 507 │ except BaseException as error: │ │ 508 │ │ # Transformers appears to handle KeyboardInterrupt (or BaseException) │ │ 509 │ │ # internally in some places, which can re-raise a different error in the handler │ │ │ │ C:\Users\phr00t\AppData\Roaming\Python\Python312\site-packages\heretic\main.py:116 in run │ │ │ │ 113 │ # Silence the warning about multivariate TPE being experimental. │ │ 114 │ warnings.filterwarnings("ignore", category=ExperimentalWarning) │ │ 115 │ │ │ ❱ 116 │ model = Model(settings) │ │ 117 │ │ │ 118 │ print() │ │ 119 │ print(f"Loading good prompts from [bold]{settings.good_prompts.dataset}[/]...") │ │ │ │ C:\Users\phr00t\AppData\Roaming\Python\Python312\site-packages\heretic\model.py:76 in __init__ │ │ │ │ 73 │ │ │ break │ │ 74 │ │ │ │ 75 │ │ if self.model is None: │ │ ❱ 76 │ │ │ raise Exception("Failed to load model with all configured dtypes.") │ │ 77 │ │ │ │ 78 │ │ print(f"* Transformer model with [bold]{len(self.get_layers())}[/] layers") │ │ 79 │ │ print("* Abliterable components:") │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯ Exception: Failed to load model with all configured dtypes.`
bsakaguchi 2026-11-01 04:16:27 +07:00
Author
Owner

@yxtann commented on GitHub (Nov 18, 2025):

I manually added the Qwen3VLForConditionalGeneration and AutoProcessor in, and did a hacky nested try except to get it to load the VL model. You can refer here for model.py

# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (C) 2025  Philipp Emanuel Weidmann <pew@worldwidemann.com>

import math
from contextlib import suppress
from dataclasses import dataclass
from typing import Any

import torch
import torch.nn.functional as F
from torch import LongTensor, Tensor
from torch.nn import ModuleList
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    BatchEncoding,
    PreTrainedTokenizerBase,
    TextStreamer,
    Qwen3VLForConditionalGeneration,
    AutoProcessor,
)
from transformers.generation.utils import GenerateOutput

from .config import Settings
from .utils import batchify, empty_cache, print


@dataclass
class AbliterationParameters:
    max_weight: float
    max_weight_position: float
    min_weight: float
    min_weight_distance: float


class Model:
    def __init__(self, settings: Settings):
        self.settings = settings

        print()
        print(f"Loading model [bold]{settings.model}[/]...")

        try:
            self.tokenizer: PreTrainedTokenizerBase = AutoTokenizer.from_pretrained(
                settings.model
            )
        except Exception as error:
            try: 
                self.tokenizer: PreTrainedTokenizerBase = AutoProcessor.from_pretrained(
                    settings.model
                )
            except Exception as error:
                raise Exception(f"Failed to load tokenizer: {error}")

        # Fallback for tokenizers that don't declare a special pad token.
        if self.tokenizer.pad_token is None:
            self.tokenizer.pad_token = self.tokenizer.eos_token
            self.tokenizer.padding_side = "left"

        self.model = None

        for dtype in settings.dtypes:
            print(f"* Trying dtype [bold]{dtype}[/]... ", end="")

            try:
                self.model = AutoModelForCausalLM.from_pretrained(
                    settings.model,
                    dtype=dtype,
                    device_map=settings.device_map,
                )

                # A test run can reveal dtype-related problems such as the infamous
                # "RuntimeError: probability tensor contains either `inf`, `nan` or element < 0"
                # (https://github.com/meta-llama/llama/issues/380).
                self.generate(["Test"], max_new_tokens=1)

            except Exception as error:

                try: 
                    self.model = Qwen3VLForConditionalGeneration.from_pretrained(
                        settings.model,
                        dtype=dtype,
                        device_map=settings.device_map,
                    )
                except Exception as error:
                    self.model = None
                    empty_cache()
                    print(f"[red]Failed[/] ({error})")
                    continue

            print("[green]Ok[/]")
            break

        if self.model is None:
            raise Exception("Failed to load model with all configured dtypes.")

        print(f"* Transformer model with [bold]{len(self.get_layers())}[/] layers")
        print("* Abliterable components:")
        for component, matrices in self.get_layer_matrices(0).items():
            print(
                f"  * [bold]{component}[/]: [bold]{len(matrices)}[/] matrices per layer"
            )

    def reload_model(self):
        dtype = self.model.dtype

        # Purge existing model object from memory to make space.
        self.model = None
        empty_cache()

        try:
            self.model = AutoModelForCausalLM.from_pretrained(
                self.settings.model,
                dtype=dtype,
                device_map=self.settings.device_map,
            )
        except Exception as error:
            try: 
                self.model = Qwen3VLForConditionalGeneration.from_pretrained(
                    self.settings.model,
                    dtype=dtype,
                    device_map=self.settings.device_map,
                )
            except Exception as error:
                raise Exception(f"Failed to reload model: {error}")

    def get_layers(self) -> ModuleList:
        # Most multimodal models.
        with suppress(Exception):
            return self.model.model.language_model.layers

        # Text-only models.
        return self.model.model.layers

    def get_layer_matrices(self, layer_index: int) -> dict[str, list[Tensor]]:
        layer = self.get_layers()[layer_index]

        matrices = {}

        def try_add(component: str, matrix: Any):
            assert torch.is_tensor(matrix)

            if component not in matrices:
                matrices[component] = []

            matrices[component].append(matrix)

        # Exceptions aren't suppressed here, because there is currently
        # no alternative location for the attention out-projection.
        try_add("attn.o_proj", layer.self_attn.o_proj.weight)

        # Most dense models.
        with suppress(Exception):
            try_add("mlp.down_proj", layer.mlp.down_proj.weight)

        # Some MoE models (e.g. Qwen3).
        with suppress(Exception):
            for expert in layer.mlp.experts:
                try_add("mlp.down_proj", expert.down_proj.weight)

        # Phi-3.5-MoE (and possibly others).
        with suppress(Exception):
            for expert in layer.block_sparse_moe.experts:
                try_add("mlp.down_proj", expert.w2.weight)

        # gpt-oss MoE.
        with suppress(Exception):
            # The implementation of gpt-oss in Transformers differs from many other MoE models
            # in that it stores the down-projections for all experts in a single 3D tensor,
            # but thanks to PyTorch's broadcasting magic, it all just works anyway.
            try_add("mlp.down_proj", layer.mlp.experts.down_proj)

        # We need at least one MLP down-projection.
        assert matrices["mlp.down_proj"]

        return matrices

    def get_abliterable_components(self) -> list[str]:
        return list(self.get_layer_matrices(0).keys())

    def abliterate(
        self,
        refusal_directions: Tensor,
        direction_index: float | None,
        parameters: dict[str, AbliterationParameters],
    ):
        if direction_index is None:
            refusal_direction = None
        else:
            # The index must be shifted by 1 because the first element
            # of refusal_directions is the direction for the embeddings.
            weight, index = math.modf(direction_index + 1)
            refusal_direction = F.normalize(
                refusal_directions[int(index)].lerp(
                    refusal_directions[int(index) + 1],
                    weight,
                ),
                p=2,
                dim=0,
            )

        # Note that some implementations of abliteration also orthogonalize
        # the embedding matrix, but it's unclear if that has any benefits.
        for layer_index in range(len(self.get_layers())):
            for component, matrices in self.get_layer_matrices(layer_index).items():
                params = parameters[component]

                distance = abs(layer_index - params.max_weight_position)

                # Don't orthogonalize layers that are more than
                # min_weight_distance away from max_weight_position.
                if distance > params.min_weight_distance:
                    continue

                # Interpolate linearly between max_weight and min_weight
                # over min_weight_distance.
                weight = params.max_weight + (distance / params.min_weight_distance) * (
                    params.min_weight - params.max_weight
                )

                if refusal_direction is None:
                    # The index must be shifted by 1 because the first element
                    # of refusal_directions is the direction for the embeddings.
                    layer_refusal_direction = refusal_directions[layer_index + 1]
                else:
                    layer_refusal_direction = refusal_direction

                # Projects any right-multiplied vector(s) onto the subspace
                # spanned by the refusal direction.
                projector = torch.outer(
                    layer_refusal_direction,
                    layer_refusal_direction,
                ).to(self.model.dtype)

                for matrix in matrices:
                    # In-place subtraction is safe as we're not using Autograd.
                    matrix.sub_(weight * (projector @ matrix))

    def get_chat(self, prompt: str) -> list[dict[str, str]]:
        return [
            {"role": "system", "content": self.settings.system_prompt},
            {"role": "user", "content": prompt},
        ]

    def generate(
        self,
        prompts: list[str],
        **kwargs: Any,
    ) -> tuple[BatchEncoding, GenerateOutput | LongTensor]:
        chats = [self.get_chat(prompt) for prompt in prompts]

        chat_prompts: list[str] = self.tokenizer.apply_chat_template(
            chats,
            add_generation_prompt=True,
            tokenize=False,
        )

        inputs = self.tokenizer(
            chat_prompts,
            return_tensors="pt",
            padding=True,
            return_token_type_ids=False,
        ).to(self.model.device)

        return inputs, self.model.generate(
            **inputs,
            **kwargs,
            pad_token_id=self.tokenizer.eos_token_id,
            do_sample=False,  # Use greedy decoding to ensure deterministic outputs.
        )

    def get_responses(self, prompts: list[str]) -> list[str]:
        inputs, outputs = self.generate(
            prompts,
            max_new_tokens=self.settings.max_response_length,
        )

        # Return only the newly generated part.
        return self.tokenizer.batch_decode(
            outputs[:, inputs["input_ids"].shape[1] :],
            skip_special_tokens=True,
        )

    def get_responses_batched(self, prompts: list[str]) -> list[str]:
        responses = []

        for batch in batchify(prompts, self.settings.batch_size):
            for response in self.get_responses(batch):
                responses.append(response)

        return responses

    def get_residuals(self, prompts: list[str]) -> Tensor:
        # We only generate one token, and we return the residual vectors
        # at that token position, for each prompt and layer.
        _, outputs = self.generate(
            prompts,
            max_new_tokens=1,
            output_hidden_states=True,
            return_dict_in_generate=True,
        )

        # Hidden states for the first (only) generated token.
        hidden_states = outputs.hidden_states[0]

        # The returned tensor has shape (prompt, layer, component).
        residuals = torch.stack(
            # layer_hidden_states has shape (prompt, position, component),
            # so this extracts the hidden states at the end of each prompt,
            # and stacks them up over the layers.
            [layer_hidden_states[:, -1, :] for layer_hidden_states in hidden_states],
            dim=1,
        )

        # Upcast the data type to avoid precision (bfloat16) or range (float16)
        # problems during calculations involving residual vectors.
        return residuals.to(torch.float32)

    def get_residuals_batched(self, prompts: list[str]) -> Tensor:
        residuals = []

        for batch in batchify(prompts, self.settings.batch_size):
            residuals.append(self.get_residuals(batch))

        return torch.cat(residuals, dim=0)

    # We work with logprobs rather than probabilities for numerical stability
    # when computing the KL divergence.
    def get_logprobs(self, prompts: list[str]) -> Tensor:
        # We only generate one token, and we return the (log) probability distributions
        # over the vocabulary at that token position, for each prompt.
        _, outputs = self.generate(
            prompts,
            max_new_tokens=1,
            output_scores=True,
            return_dict_in_generate=True,
        )

        # Logits for the first (only) generated token.
        logits = outputs.scores[0]

        # The returned tensor has shape (prompt, token).
        return F.log_softmax(logits, dim=-1)

    def get_logprobs_batched(self, prompts: list[str]) -> Tensor:
        logprobs = []

        for batch in batchify(prompts, self.settings.batch_size):
            logprobs.append(self.get_logprobs(batch))

        return torch.cat(logprobs, dim=0)

    def stream_chat_response(self, chat: list[dict[str, str]]) -> str:
        chat_prompt: str = self.tokenizer.apply_chat_template(
            chat,
            add_generation_prompt=True,
            tokenize=False,
        )

        inputs = self.tokenizer(
            chat_prompt,
            return_tensors="pt",
            return_token_type_ids=False,
        ).to(self.model.device)

        streamer = TextStreamer(
            self.tokenizer,
            skip_prompt=True,
            skip_special_tokens=True,
        )

        outputs = self.model.generate(
            **inputs,
            streamer=streamer,
            max_new_tokens=4096,
        )

        return self.tokenizer.decode(
            outputs[0, inputs["input_ids"].shape[1] :],
            skip_special_tokens=True,
        )
<!-- gh-comment-id:3544939639 --> @yxtann commented on GitHub (Nov 18, 2025): I manually added the `Qwen3VLForConditionalGeneration` and `AutoProcessor` in, and did a hacky nested try except to get it to load the VL model. You can refer here for `model.py` ```python # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025 Philipp Emanuel Weidmann <pew@worldwidemann.com> import math from contextlib import suppress from dataclasses import dataclass from typing import Any import torch import torch.nn.functional as F from torch import LongTensor, Tensor from torch.nn import ModuleList from transformers import ( AutoModelForCausalLM, AutoTokenizer, BatchEncoding, PreTrainedTokenizerBase, TextStreamer, Qwen3VLForConditionalGeneration, AutoProcessor, ) from transformers.generation.utils import GenerateOutput from .config import Settings from .utils import batchify, empty_cache, print @dataclass class AbliterationParameters: max_weight: float max_weight_position: float min_weight: float min_weight_distance: float class Model: def __init__(self, settings: Settings): self.settings = settings print() print(f"Loading model [bold]{settings.model}[/]...") try: self.tokenizer: PreTrainedTokenizerBase = AutoTokenizer.from_pretrained( settings.model ) except Exception as error: try: self.tokenizer: PreTrainedTokenizerBase = AutoProcessor.from_pretrained( settings.model ) except Exception as error: raise Exception(f"Failed to load tokenizer: {error}") # Fallback for tokenizers that don't declare a special pad token. if self.tokenizer.pad_token is None: self.tokenizer.pad_token = self.tokenizer.eos_token self.tokenizer.padding_side = "left" self.model = None for dtype in settings.dtypes: print(f"* Trying dtype [bold]{dtype}[/]... ", end="") try: self.model = AutoModelForCausalLM.from_pretrained( settings.model, dtype=dtype, device_map=settings.device_map, ) # A test run can reveal dtype-related problems such as the infamous # "RuntimeError: probability tensor contains either `inf`, `nan` or element < 0" # (https://github.com/meta-llama/llama/issues/380). self.generate(["Test"], max_new_tokens=1) except Exception as error: try: self.model = Qwen3VLForConditionalGeneration.from_pretrained( settings.model, dtype=dtype, device_map=settings.device_map, ) except Exception as error: self.model = None empty_cache() print(f"[red]Failed[/] ({error})") continue print("[green]Ok[/]") break if self.model is None: raise Exception("Failed to load model with all configured dtypes.") print(f"* Transformer model with [bold]{len(self.get_layers())}[/] layers") print("* Abliterable components:") for component, matrices in self.get_layer_matrices(0).items(): print( f" * [bold]{component}[/]: [bold]{len(matrices)}[/] matrices per layer" ) def reload_model(self): dtype = self.model.dtype # Purge existing model object from memory to make space. self.model = None empty_cache() try: self.model = AutoModelForCausalLM.from_pretrained( self.settings.model, dtype=dtype, device_map=self.settings.device_map, ) except Exception as error: try: self.model = Qwen3VLForConditionalGeneration.from_pretrained( self.settings.model, dtype=dtype, device_map=self.settings.device_map, ) except Exception as error: raise Exception(f"Failed to reload model: {error}") def get_layers(self) -> ModuleList: # Most multimodal models. with suppress(Exception): return self.model.model.language_model.layers # Text-only models. return self.model.model.layers def get_layer_matrices(self, layer_index: int) -> dict[str, list[Tensor]]: layer = self.get_layers()[layer_index] matrices = {} def try_add(component: str, matrix: Any): assert torch.is_tensor(matrix) if component not in matrices: matrices[component] = [] matrices[component].append(matrix) # Exceptions aren't suppressed here, because there is currently # no alternative location for the attention out-projection. try_add("attn.o_proj", layer.self_attn.o_proj.weight) # Most dense models. with suppress(Exception): try_add("mlp.down_proj", layer.mlp.down_proj.weight) # Some MoE models (e.g. Qwen3). with suppress(Exception): for expert in layer.mlp.experts: try_add("mlp.down_proj", expert.down_proj.weight) # Phi-3.5-MoE (and possibly others). with suppress(Exception): for expert in layer.block_sparse_moe.experts: try_add("mlp.down_proj", expert.w2.weight) # gpt-oss MoE. with suppress(Exception): # The implementation of gpt-oss in Transformers differs from many other MoE models # in that it stores the down-projections for all experts in a single 3D tensor, # but thanks to PyTorch's broadcasting magic, it all just works anyway. try_add("mlp.down_proj", layer.mlp.experts.down_proj) # We need at least one MLP down-projection. assert matrices["mlp.down_proj"] return matrices def get_abliterable_components(self) -> list[str]: return list(self.get_layer_matrices(0).keys()) def abliterate( self, refusal_directions: Tensor, direction_index: float | None, parameters: dict[str, AbliterationParameters], ): if direction_index is None: refusal_direction = None else: # The index must be shifted by 1 because the first element # of refusal_directions is the direction for the embeddings. weight, index = math.modf(direction_index + 1) refusal_direction = F.normalize( refusal_directions[int(index)].lerp( refusal_directions[int(index) + 1], weight, ), p=2, dim=0, ) # Note that some implementations of abliteration also orthogonalize # the embedding matrix, but it's unclear if that has any benefits. for layer_index in range(len(self.get_layers())): for component, matrices in self.get_layer_matrices(layer_index).items(): params = parameters[component] distance = abs(layer_index - params.max_weight_position) # Don't orthogonalize layers that are more than # min_weight_distance away from max_weight_position. if distance > params.min_weight_distance: continue # Interpolate linearly between max_weight and min_weight # over min_weight_distance. weight = params.max_weight + (distance / params.min_weight_distance) * ( params.min_weight - params.max_weight ) if refusal_direction is None: # The index must be shifted by 1 because the first element # of refusal_directions is the direction for the embeddings. layer_refusal_direction = refusal_directions[layer_index + 1] else: layer_refusal_direction = refusal_direction # Projects any right-multiplied vector(s) onto the subspace # spanned by the refusal direction. projector = torch.outer( layer_refusal_direction, layer_refusal_direction, ).to(self.model.dtype) for matrix in matrices: # In-place subtraction is safe as we're not using Autograd. matrix.sub_(weight * (projector @ matrix)) def get_chat(self, prompt: str) -> list[dict[str, str]]: return [ {"role": "system", "content": self.settings.system_prompt}, {"role": "user", "content": prompt}, ] def generate( self, prompts: list[str], **kwargs: Any, ) -> tuple[BatchEncoding, GenerateOutput | LongTensor]: chats = [self.get_chat(prompt) for prompt in prompts] chat_prompts: list[str] = self.tokenizer.apply_chat_template( chats, add_generation_prompt=True, tokenize=False, ) inputs = self.tokenizer( chat_prompts, return_tensors="pt", padding=True, return_token_type_ids=False, ).to(self.model.device) return inputs, self.model.generate( **inputs, **kwargs, pad_token_id=self.tokenizer.eos_token_id, do_sample=False, # Use greedy decoding to ensure deterministic outputs. ) def get_responses(self, prompts: list[str]) -> list[str]: inputs, outputs = self.generate( prompts, max_new_tokens=self.settings.max_response_length, ) # Return only the newly generated part. return self.tokenizer.batch_decode( outputs[:, inputs["input_ids"].shape[1] :], skip_special_tokens=True, ) def get_responses_batched(self, prompts: list[str]) -> list[str]: responses = [] for batch in batchify(prompts, self.settings.batch_size): for response in self.get_responses(batch): responses.append(response) return responses def get_residuals(self, prompts: list[str]) -> Tensor: # We only generate one token, and we return the residual vectors # at that token position, for each prompt and layer. _, outputs = self.generate( prompts, max_new_tokens=1, output_hidden_states=True, return_dict_in_generate=True, ) # Hidden states for the first (only) generated token. hidden_states = outputs.hidden_states[0] # The returned tensor has shape (prompt, layer, component). residuals = torch.stack( # layer_hidden_states has shape (prompt, position, component), # so this extracts the hidden states at the end of each prompt, # and stacks them up over the layers. [layer_hidden_states[:, -1, :] for layer_hidden_states in hidden_states], dim=1, ) # Upcast the data type to avoid precision (bfloat16) or range (float16) # problems during calculations involving residual vectors. return residuals.to(torch.float32) def get_residuals_batched(self, prompts: list[str]) -> Tensor: residuals = [] for batch in batchify(prompts, self.settings.batch_size): residuals.append(self.get_residuals(batch)) return torch.cat(residuals, dim=0) # We work with logprobs rather than probabilities for numerical stability # when computing the KL divergence. def get_logprobs(self, prompts: list[str]) -> Tensor: # We only generate one token, and we return the (log) probability distributions # over the vocabulary at that token position, for each prompt. _, outputs = self.generate( prompts, max_new_tokens=1, output_scores=True, return_dict_in_generate=True, ) # Logits for the first (only) generated token. logits = outputs.scores[0] # The returned tensor has shape (prompt, token). return F.log_softmax(logits, dim=-1) def get_logprobs_batched(self, prompts: list[str]) -> Tensor: logprobs = [] for batch in batchify(prompts, self.settings.batch_size): logprobs.append(self.get_logprobs(batch)) return torch.cat(logprobs, dim=0) def stream_chat_response(self, chat: list[dict[str, str]]) -> str: chat_prompt: str = self.tokenizer.apply_chat_template( chat, add_generation_prompt=True, tokenize=False, ) inputs = self.tokenizer( chat_prompt, return_tensors="pt", return_token_type_ids=False, ).to(self.model.device) streamer = TextStreamer( self.tokenizer, skip_prompt=True, skip_special_tokens=True, ) outputs = self.model.generate( **inputs, streamer=streamer, max_new_tokens=4096, ) return self.tokenizer.decode( outputs[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True, ) ```
Author
Owner

@p-e-w commented on GitHub (Nov 18, 2025):

I don't get it. How does that normally work then? I'm using the bog standard Transformer loading method that is supposed to work with all models. From their model card, it appears that they indeed don't support AutoModelForCausalLM.

<!-- gh-comment-id:3544965920 --> @p-e-w commented on GitHub (Nov 18, 2025): I don't get it. How does that normally work then? I'm using the bog standard Transformer loading method that is supposed to work with all models. From their model card, it appears that they indeed don't support `AutoModelForCausalLM`.
Author
Owner

@yxtann commented on GitHub (Nov 18, 2025):

There might have been a proper fix here in the transformers library, but I don't think it is pushed to the official releases. I'm not sure though, did not test the Heretic repo with the latest transformers main branch. I'm using transformers==4.57.1 currently.

https://github.com/huggingface/transformers/pull/42059

<!-- gh-comment-id:3545021293 --> @yxtann commented on GitHub (Nov 18, 2025): There might have been a proper fix here in the `transformers` library, but I don't think it is pushed to the official releases. I'm not sure though, did not test the Heretic repo with the latest transformers main branch. I'm using `transformers==4.57.1` currently. https://github.com/huggingface/transformers/pull/42059
Author
Owner

@jeancmyk commented on GitHub (Nov 19, 2025):

I was able to modify the model.py file as described below, and it worked so I abliterated qwen3 4b vl using your method. Will upload to HF later. I used gemini 3 to fix this, and have no idea how or why it works. EDIT: I am running this in a virtual environment on Win 11 using Python 3.12.9 PyTorch Nightly Build 2.5.1+cu121 (bc rtx 5090) CUDA 12.1.

https://huggingface.co/JSon-AI/Qwen3-VL-4B-Instruct-Abliterated-heretic

Also attached the updated model.py below. Thanks for developing this user-friendly tool!


Issue:
The tool currently hardcodes AutoModelForCausalLM. This causes a crash when trying to load Vision-Language models (e.g., Qwen/Qwen3-VL-4B-Instruct) which require AutoModelForVision2Seq. Additionally, reload_model() hardcodes the loader, which causes the tool to crash during the optimization phase even if the initial load succeeds.

Solution:

  1. Import AutoModelForVision2Seq.
  2. Add a fallback in __init__ to try the Vision loader if the CausalLM loader fails.
  3. Update reload_model to dynamically use the active model's class instead of hardcoding the loader.

Changes in model.py:

1. Update Imports

from transformers import (
    AutoModelForCausalLM,
    AutoModelForVision2Seq,  # <--- Added
    AutoTokenizer,
    # ...
)

2. Update __init__ (Fallback Logic)
Replace the existing loading loop with:

        for dtype in settings.dtypes:
            print(f"* Trying dtype [bold]{dtype}[/]... ", end="")

            try:
                # Try CausalLM first
                self.model = AutoModelForCausalLM.from_pretrained(
                    settings.model,
                    dtype=dtype,
                    device_map=settings.device_map,
                    trust_remote_code=True
                )
                self.generate(["Test"], max_new_tokens=1)
            except Exception:
                # Fallback to Vision2Seq
                try:
                    if self.model is not None: del self.model
                    empty_cache()
                    
                    self.model = AutoModelForVision2Seq.from_pretrained(
                        settings.model,
                        dtype=dtype,
                        device_map=settings.device_map,
                        trust_remote_code=True
                    )
                    self.generate(["Test"], max_new_tokens=1)
                except Exception:
                    self.model = None
                    empty_cache()
                    print(f"[red]Failed[/]")
                    continue

            print("[green]Ok[/]")
            break

3. Update reload_model (Dynamic Class Loading)
Replace the reload_model method with:

    def reload_model(self):
        dtype = self.model.dtype
        
        # Use the current model's class (CausalLM or Vision2Seq) to ensure consistency
        ModelClass = self.model.__class__

        self.model = None
        empty_cache()

        self.model = ModelClass.from_pretrained(
            self.settings.model,
            dtype=dtype,
            device_map=self.settings.device_map,
            trust_remote_code=True
        )

model_modified.py

<!-- gh-comment-id:3550228598 --> @jeancmyk commented on GitHub (Nov 19, 2025): I was able to modify the model.py file as described below, and it worked so I abliterated qwen3 4b vl using your method. Will upload to HF later. I used gemini 3 to fix this, and have no idea how or why it works. EDIT: I am running this in a virtual environment on Win 11 using Python 3.12.9 PyTorch Nightly Build 2.5.1+cu121 (bc rtx 5090) CUDA 12.1. https://huggingface.co/JSon-AI/Qwen3-VL-4B-Instruct-Abliterated-heretic Also attached the updated model.py below. Thanks for developing this user-friendly tool! *** **Issue:** The tool currently hardcodes `AutoModelForCausalLM`. This causes a crash when trying to load Vision-Language models (e.g., `Qwen/Qwen3-VL-4B-Instruct`) which require `AutoModelForVision2Seq`. Additionally, `reload_model()` hardcodes the loader, which causes the tool to crash during the optimization phase even if the initial load succeeds. **Solution:** 1. Import `AutoModelForVision2Seq`. 2. Add a fallback in `__init__` to try the Vision loader if the CausalLM loader fails. 3. Update `reload_model` to dynamically use the active model's class instead of hardcoding the loader. **Changes in `model.py`:** **1. Update Imports** ```python from transformers import ( AutoModelForCausalLM, AutoModelForVision2Seq, # <--- Added AutoTokenizer, # ... ) ``` **2. Update `__init__` (Fallback Logic)** *Replace the existing loading loop with:* ```python for dtype in settings.dtypes: print(f"* Trying dtype [bold]{dtype}[/]... ", end="") try: # Try CausalLM first self.model = AutoModelForCausalLM.from_pretrained( settings.model, dtype=dtype, device_map=settings.device_map, trust_remote_code=True ) self.generate(["Test"], max_new_tokens=1) except Exception: # Fallback to Vision2Seq try: if self.model is not None: del self.model empty_cache() self.model = AutoModelForVision2Seq.from_pretrained( settings.model, dtype=dtype, device_map=settings.device_map, trust_remote_code=True ) self.generate(["Test"], max_new_tokens=1) except Exception: self.model = None empty_cache() print(f"[red]Failed[/]") continue print("[green]Ok[/]") break ``` **3. Update `reload_model` (Dynamic Class Loading)** *Replace the `reload_model` method with:* ```python def reload_model(self): dtype = self.model.dtype # Use the current model's class (CausalLM or Vision2Seq) to ensure consistency ModelClass = self.model.__class__ self.model = None empty_cache() self.model = ModelClass.from_pretrained( self.settings.model, dtype=dtype, device_map=self.settings.device_map, trust_remote_code=True ) ``` [model_modified.py](https://github.com/user-attachments/files/23616874/model_modified.py)
Author
Owner

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

@jeancmyk

Thanks for the effort, but I think the correct solution here is to wait for Transformers to fix this upstream. AutoModelForCausalLM is the officially blessed mechanism that is supposed to load any model that contains a generative language model. This also works for most multimodal models such as Gemma 3. The fact that it doesn't load Qwen3 VL is a defect in Transformers, and should be addressed there.

I'm going to wait a few months, and if Transformers doesn't address this, I'll revisit and consider adopting your workaround.

<!-- gh-comment-id:3550379555 --> @p-e-w commented on GitHub (Nov 19, 2025): @jeancmyk Thanks for the effort, but I think the correct solution here is to wait for Transformers to fix this upstream. `AutoModelForCausalLM` is the officially blessed mechanism that is supposed to load *any* model that contains a generative language model. This also works for most multimodal models such as Gemma 3. The fact that it doesn't load Qwen3 VL is a defect in Transformers, and should be addressed there. I'm going to wait a few months, and if Transformers doesn't address this, I'll revisit and consider adopting your workaround.
Author
Owner
<!-- gh-comment-id:3566996720 --> @coder3101 commented on GitHub (Nov 22, 2025): https://huggingface.co/coder3101/Qwen3-VL-32B-Instruct-Heretic EDIT: I abliterated bunch of other models in Qwen3VL - here you go! - https://huggingface.co/collections/coder3101/qwen3-vl-instruct-heretic - https://huggingface.co/collections/coder3101/qwen3-vl-thinking-heretic
Author
Owner

@TomLucidor commented on GitHub (Dec 10, 2025):

If this is real, then Qwen-Image-Edit and SAM3 would be free to detect things too, no?

<!-- gh-comment-id:3637388823 --> @TomLucidor commented on GitHub (Dec 10, 2025): If this is real, then Qwen-Image-Edit and SAM3 would be free to detect things too, no?
Author
Owner

@raziel2001au commented on GitHub (Dec 21, 2025):

@jeancmyk

Thanks for the effort, but I think the correct solution here is to wait for Transformers to fix this upstream. AutoModelForCausalLM is the officially blessed mechanism that is supposed to load any model that contains a generative language model. This also works for most multimodal models such as Gemma 3. The fact that it doesn't load Qwen3 VL is a defect in Transformers, and should be addressed there.

I'm going to wait a few months, and if Transformers doesn't address this, I'll revisit and consider adopting your workaround.

It's not going to get 'fixed', from my understanding, for VL models, you are supposed to use 'AutoModelForImageTextToText' rather than the normal 'AutoModelForCausalLM', for more information, refer to the documentation on image text to text (i.e. VL models): https://huggingface.co/docs/transformers/main/tasks/image_text_to_text

<!-- gh-comment-id:3678511515 --> @raziel2001au commented on GitHub (Dec 21, 2025): > [@jeancmyk](https://github.com/jeancmyk) > > Thanks for the effort, but I think the correct solution here is to wait for Transformers to fix this upstream. `AutoModelForCausalLM` is the officially blessed mechanism that is supposed to load _any_ model that contains a generative language model. This also works for most multimodal models such as Gemma 3. The fact that it doesn't load Qwen3 VL is a defect in Transformers, and should be addressed there. > > I'm going to wait a few months, and if Transformers doesn't address this, I'll revisit and consider adopting your workaround. It's not going to get 'fixed', from my understanding, for VL models, you are supposed to use 'AutoModelForImageTextToText' rather than the normal 'AutoModelForCausalLM', for more information, refer to the documentation on image text to text (i.e. VL models): https://huggingface.co/docs/transformers/main/tasks/image_text_to_text
Author
Owner

@p-e-w commented on GitHub (Jan 23, 2026):

Fixed by @anrp in #108.

<!-- gh-comment-id:3790409230 --> @p-e-w commented on GitHub (Jan 23, 2026): Fixed by @anrp in #108.
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#8
No description provided.