feat: add MLX backend for native Apple Silicon abliteration#226
feat: add MLX backend for native Apple Silicon abliteration#226overtimepog wants to merge 6 commits intop-e-w:masterfrom
Conversation
Adds a complete MLX backend that enables heretic to run abliteration natively on Apple Silicon using the MLX framework and mlx-lm library. This allows direct use of MLX-format quantized models (e.g. 4-bit safetensors) without conversion, taking advantage of Metal GPU acceleration and unified memory. Key changes: - New `MLXModel` class (`mlx_model.py`) implementing the full model interface: loading, generation, hidden state extraction, logprob computation, abliteration via dequantize-modify-requantize, weight reset, model saving, and streaming chat - `Backend` enum (AUTO/PYTORCH/MLX) in config with auto-detection of MLX model format - Backend resolution and model factory in main.py with MLX device detection and memory reporting - MLX optional dependency group: `pip install heretic-llm[mlx]` - 31 tests (unit + integration) covering all operations including MoE architecture support (tested with Qwen3-Coder-30B-A3B MoE) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
|
Warning Gemini encountered an error creating the review. You can try again by commenting |
- Fix LM head projection for models with tie_word_embeddings=true (e.g. Llama, SmolLM) that reuse the embedding matrix instead of having a separate lm_head layer - Add 14 PyTorch fallback tests verifying MLX imports are lazy and the PyTorch code path is unaffected when MLX is unavailable - Tested with SmolLM2-135M-Instruct (LlamaForCausalLM, dense) in addition to Qwen3-Coder-30B-A3B (Qwen3MoeForCausalLM, MoE) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…Backend The existing code uses `backend` for the JournalFileBackend object. The new resolve_backend() return value was also named `backend`, causing it to be overwritten before create_model() was called. Renamed to `model_backend` to avoid the conflict. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replace full-tensor dequantization with per-expert processing: each of the 128 experts is dequantized, modified, and requantized individually, keeping peak memory bounded. Reduces abliteration memory spike from 16+ GB (OOM on 32GB systems) to ~5 GB. Also fix deprecated mx.metal.* calls to use mx.get_peak_memory() and mx.get_active_memory() directly. Adds memory budget integration tests (test_mlx_memory.py). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Monkey-patch mx.metal.device_info/get_peak_memory/get_active_memory to their current mx.* equivalents before mlx_lm uses them, silencing C++ deprecation warnings that bypass Python's warnings module. Add run_mlx.sh convenience script for running heretic with MLX backend. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Use mlx_lm.batch_generate() for response generation instead of sequential per-prompt mlx_lm.generate() calls - Add _forward_logits_only() that uses the model's optimized __call__ for logprob computation instead of the slower layer-by-layer pass - These two changes eliminate the biggest bottlenecks in the abliteration pipeline (prefix check, evaluation, refusal counting) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Summary
backend = "auto"(default), or can be explicitly set with--backend mlxChanges
New files
src/heretic/mlx_model.py(~660 lines) — Full MLX model backend implementing the same interface as the PyTorchModelclass:mlx_lm.load()Linearand MoESwitchLinear/QuantizedSwitchLinear)tests/test_mlx_model.py— 31 tests (6 unit + 25 integration) covering all operationsModified files
config.py— AddedBackendenum (AUTO/PYTORCH/MLX) with defaultAUTOmain.py— Addedresolve_backend(),create_model()factory, MLX device detection, and MLX-aware save/upload flowsutils.py— Added MLX memory reporting (get_peak_memory,get_active_memory)pyproject.toml— Added[mlx]optional dependency group, pytest marker configconfig.default.toml— Documented the newbackendsettingDesign decisions
torch.Tensorat the interface boundary soevaluator.pyandmain.pywork unchangedBackend.PYTORCHpath is completely unchangedMoE support
Tested with Qwen3-Coder-30B-A3B-Instruct-MLX-4bit (128 experts, 8 active per token, 48 layers). Handles:
SwitchGLU/QuantizedSwitchLinearstacked expert weightsmx.einsumfor efficient vectorized computationTest plan
Usage
🤖 Generated with Claude Code