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 #516] Headless apply-and-save: interactive tail deadlocks without a TTY — working recipe + driver (validated on Qwen3-VL-8B) #222

Closed
opened 2026-11-01 04:18:46 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @belo-labs on GitHub (Oct 22, 2026).
Original GitHub issue: https://github.com/p-e-w/heretic/issues/516

Version

heretic-llm 1.4.0

Problem

The end of a search run — apply the winning trial and save the merged model — is an interactive TUI flow. Under any non-interactive driver it deadlocks: driving keystrokes through a fifo into the process (no TTY) gets as far as the parameter-restore printout and then blocks forever on a hidden questionary/rich prompt. Launching under a pty via script -qec keeps the search alive but does not help the apply-and-save tail. Anything running heretic in automation (sweeps, CI, overnight batch) hits this.

Working headless recipe

The apply step lifts main.py's own restore flow verbatim, minus the TUI — no TTY anywhere. Full driver (validated end-to-end: Qwen3-VL-8B-Instruct, 200-trial journal → applied trial 51 → saved → converted F16→Q4_K_M; the build then gated at −1 task vs its censored base on a 127-task suite, so the restore is faithful):

#!/usr/bin/env python3
"""Headless heretic apply: journal trial N -> abliterate -> save merged model."""
import torch
import optuna
from optuna.storages.journal import JournalFileBackend, JournalFileOpenLock
from torch.nn import functional as F

from heretic.config import Settings, QuantizationMethod
from heretic.model import Model, AbliterationParameters

MODEL = "huihui-ai/Huihui-Qwen3-VL-8B-Instruct-abliterated"   # any model you searched
JOURNAL = "/path/to/checkpoints/<model>.jsonl"
OUT = "/path/to/out-dir"
TRIAL_INDEX = 51                                              # the trial.user_attrs["index"] you want

settings = Settings(model=MODEL, quantization=QuantizationMethod.BNB_4BIT, batch_size=4, seed=42)

model = Model(settings)

from heretic.main import load_prompts
good_prompts = load_prompts(settings, settings.good_prompts)
bad_prompts = load_prompts(settings, settings.bad_prompts)

good_means = model.get_residuals_mean(good_prompts)
bad_means = model.get_residuals_mean(bad_prompts)
refusal_directions = F.normalize(bad_means - good_means, p=2, dim=1)
if settings.orthogonalize_direction:
    good_directions = F.normalize(good_means, p=2, dim=1)
    projection_vector = torch.sum(refusal_directions * good_directions, dim=1)
    refusal_directions = refusal_directions - projection_vector.unsqueeze(1) * good_directions
    refusal_directions = F.normalize(refusal_directions, p=2, dim=1)
del good_means, bad_means

backend = JournalFileBackend(JOURNAL, lock_obj=JournalFileOpenLock(JOURNAL))
storage = optuna.storages.JournalStorage(backend)
study = optuna.load_study(study_name="heretic", storage=storage)
trial = next(t for t in study.trials if t.user_attrs.get("index") == TRIAL_INDEX)
params = {k: AbliterationParameters(**v) for k, v in trial.user_attrs["parameters"].items()}

model.reset_model()
model.abliterate(refusal_directions, trial.user_attrs["direction_index"], params)

merged = model.get_merged_model()
merged.save_pretrained(OUT, max_shard_size=settings.max_shard_size)
model.tokenizer.save_pretrained(OUT)
if model.processor is not None:
    model.processor.save_pretrained(OUT)

Notes collected while making this work (all reproducible gotchas)

  1. Settings requires model at construction (pydantic validation), and seed=None crashes torch.manual_seed — pass an integer seed even when you don't care.
  2. The post-restore processor.save_pretrained(OUT) omits preprocessor_config.json (only video_preprocessor_config.json lands). convert_hf_to_gguf --mmproj needs it — copy it from the source repo before conversion.
  3. convert_hf_to_gguf --mmproj exports only the projector; run it in default mode for the main model.
  4. Clean quantize chain: save F16 first, then llama-quantize to the target type (Q4_K_M here) — quantizing directly from the merged in-memory save was not attempted, F16-first is the tested path.

If this is useful upstream, happy to turn it into a PR — a --reproduce <index> -o <dir> flag on the CLI (reusing exactly this flow) would make the whole post-search tail automation-friendly.

Originally created by @belo-labs on GitHub (Oct 22, 2026). Original GitHub issue: https://github.com/p-e-w/heretic/issues/516 ### Version heretic-llm 1.4.0 ### Problem The end of a search run — apply the winning trial and save the merged model — is an interactive TUI flow. Under any non-interactive driver it deadlocks: driving keystrokes through a fifo into the process (no TTY) gets as far as the parameter-restore printout and then blocks forever on a hidden `questionary`/rich prompt. Launching under a pty via `script -qec` keeps the *search* alive but does not help the apply-and-save tail. Anything running heretic in automation (sweeps, CI, overnight batch) hits this. ### Working headless recipe The apply step lifts `main.py`'s own restore flow verbatim, minus the TUI — no TTY anywhere. Full driver (validated end-to-end: Qwen3-VL-8B-Instruct, 200-trial journal → applied trial 51 → saved → converted F16→Q4_K_M; the build then gated at −1 task vs its censored base on a 127-task suite, so the restore is faithful): ```python #!/usr/bin/env python3 """Headless heretic apply: journal trial N -> abliterate -> save merged model.""" import torch import optuna from optuna.storages.journal import JournalFileBackend, JournalFileOpenLock from torch.nn import functional as F from heretic.config import Settings, QuantizationMethod from heretic.model import Model, AbliterationParameters MODEL = "huihui-ai/Huihui-Qwen3-VL-8B-Instruct-abliterated" # any model you searched JOURNAL = "/path/to/checkpoints/<model>.jsonl" OUT = "/path/to/out-dir" TRIAL_INDEX = 51 # the trial.user_attrs["index"] you want settings = Settings(model=MODEL, quantization=QuantizationMethod.BNB_4BIT, batch_size=4, seed=42) model = Model(settings) from heretic.main import load_prompts good_prompts = load_prompts(settings, settings.good_prompts) bad_prompts = load_prompts(settings, settings.bad_prompts) good_means = model.get_residuals_mean(good_prompts) bad_means = model.get_residuals_mean(bad_prompts) refusal_directions = F.normalize(bad_means - good_means, p=2, dim=1) if settings.orthogonalize_direction: good_directions = F.normalize(good_means, p=2, dim=1) projection_vector = torch.sum(refusal_directions * good_directions, dim=1) refusal_directions = refusal_directions - projection_vector.unsqueeze(1) * good_directions refusal_directions = F.normalize(refusal_directions, p=2, dim=1) del good_means, bad_means backend = JournalFileBackend(JOURNAL, lock_obj=JournalFileOpenLock(JOURNAL)) storage = optuna.storages.JournalStorage(backend) study = optuna.load_study(study_name="heretic", storage=storage) trial = next(t for t in study.trials if t.user_attrs.get("index") == TRIAL_INDEX) params = {k: AbliterationParameters(**v) for k, v in trial.user_attrs["parameters"].items()} model.reset_model() model.abliterate(refusal_directions, trial.user_attrs["direction_index"], params) merged = model.get_merged_model() merged.save_pretrained(OUT, max_shard_size=settings.max_shard_size) model.tokenizer.save_pretrained(OUT) if model.processor is not None: model.processor.save_pretrained(OUT) ``` ### Notes collected while making this work (all reproducible gotchas) 1. `Settings` requires `model` at construction (pydantic validation), and `seed=None` crashes `torch.manual_seed` — pass an integer seed even when you don't care. 2. The post-restore `processor.save_pretrained(OUT)` omits `preprocessor_config.json` (only `video_preprocessor_config.json` lands). `convert_hf_to_gguf --mmproj` needs it — copy it from the source repo before conversion. 3. `convert_hf_to_gguf --mmproj` exports **only the projector**; run it in default mode for the main model. 4. Clean quantize chain: save F16 first, then `llama-quantize` to the target type (Q4_K_M here) — quantizing directly from the merged in-memory save was not attempted, F16-first is the tested path. If this is useful upstream, happy to turn it into a PR — a `--reproduce <index> -o <dir>` flag on the CLI (reusing exactly this flow) would make the whole post-search tail automation-friendly.
Author
Owner

@p-e-w commented on GitHub (Oct 22, 2026):

Heretic already supports fully headless operation through configuration. Every interactive prompt can be pre-set. In this case, the configuration key you are looking for is called trial_index:

github.com/p-e-w/heretic@09271b6202/src/heretic/config.py (L507-L510)

<!-- gh-comment-id:6345342477 --> @p-e-w commented on GitHub (Oct 22, 2026): Heretic already supports fully headless operation through configuration. Every interactive prompt can be pre-set. In this case, the configuration key you are looking for is called `trial_index`: https://github.com/p-e-w/heretic/blob/09271b620229c469d51fcdcbd57911a0cfdb72bf/src/heretic/config.py#L507-L510
Author
Owner

@belo-labs commented on GitHub (Oct 22, 2026):

Thank you — that's the cleaner path, and it supersedes the driver in my issue. For future readers hitting the same wall: the deadlock came from driving the interactive flow through a fifo; pre-setting the config keys (export_strategy, checkpoint_action, trial_index, model_action, save_directory) removes every prompt, no TTY games needed.

One detail worth knowing when coming from a journal file: trial_index is the position in the sorted Pareto front, not the raw trial's user_attrs["index"] — map the journal trial to its front position before setting it. (My driver's next(t for t in study.trials if t.user_attrs.get("index") == N) does the raw-journal equivalent.)

The driver stays useful as a library-level fallback for exotic cases (e.g. applying a trial from a journal on a different machine than the search ran on), but the config path is the right answer for normal automation. Closing this out on my side — thanks again for the pointer.

<!-- gh-comment-id:6347030667 --> @belo-labs commented on GitHub (Oct 22, 2026): Thank you — that's the cleaner path, and it supersedes the driver in my issue. For future readers hitting the same wall: the deadlock came from driving the interactive flow through a fifo; pre-setting the config keys (`export_strategy`, `checkpoint_action`, `trial_index`, `model_action`, `save_directory`) removes every prompt, no TTY games needed. One detail worth knowing when coming from a journal file: `trial_index` is the position in the *sorted Pareto front*, not the raw trial's `user_attrs["index"]` — map the journal trial to its front position before setting it. (My driver's `next(t for t in study.trials if t.user_attrs.get("index") == N)` does the raw-journal equivalent.) The driver stays useful as a library-level fallback for exotic cases (e.g. applying a trial from a journal on a different machine than the search ran on), but the config path is the right answer for normal automation. Closing this out on my side — thanks again for the pointer.
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#222
No description provided.