Skip to content
Language models

Llama-3.1-8B-Instruct-TwinDistillation

prompt injection defense

2 min readupdated

A new rank 16 LoRA (a lightweight add-on for a base model) adapter for meta-llama/Llama-3.1-8B-Instruct, trained using the twin distillation method. The model learns to tell legitimate user instructions apart from malicious instructions hidden inside processed documents. It ignores spoofed commands in the text while accurately handling core tasks like summarization or translation. This solution is built to improve LLM security when working with untrusted content.

Key features

  • Defense against indirect prompt injection across various attack scenarios.
  • Uses a dedicated prompt template that separates roles into the user task and the input document.
  • Preserves original document text during copying, counting, or translation tasks without executing hidden commands.
  • Compatible with the base Llama 3.1 8B model via standard weight-loading libraries.

What you can do

  • Safely process external documents, web pages, and emails that may contain malicious instructions.
  • Set up automated text summarization pipelines protected against prompt hijacking.
  • Integrate the model into enterprise AI assistants that read unstructured user content.

Example

from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
base = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B-Instruct", torch_dtype="bfloat16", device_map="auto")
model = PeftModel.from_pretrained(base, "anasbiswas/Llama-3.1-8B-Instruct-TwinDistillation").eval()
tok = AutoTokenizer.from_pretrained("facebook/Meta-SecAlign-8B")
SYSTEM = "You are a helpful assistant that processes the content users give you."
messages = [{"role": "system", "content": SYSTEM},
            {"role": "user", "content": "Summarise the key information in the document below."},,
            {"role": "input", "content": document_text}]
ids = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
out = model.generate(ids, max_new_tokens=160, do_sample=False)
print(tok.decode(out[0, ids.shape[1]:], skip_special_tokens=True))
Read moreDetails
BIPIA injections (fixed): 0.086 (baseline: 0.490)
BIPIA injections (adaptive): 0.000 (baseline: 0.714)
Requires accepting the Llama 3.1 license on Hugging Face
Vulnerable to white-box attacks (GCG) at a 0.040 rate
Discuss Telegram 0 12

Will it run?

Runs in BF16

Fits without quantisation.

  • BF16weights 15 GB · ready files17 GB
  • FP8 / INT8recommendedweights 7.6 GB9.0 GB
  • 4-bitweights 4.4 GB5.4 GB

Tip: go 8-bit.FP8 / INT8 is within about a percent of full precision in quality, takes half the memory and runs faster on RTX 40/50 and H100. Full precision only pays off for fine-tuning.

What to get for this model

Massed ComputeOpen Massed Compute

Your own GPU: FP8 / INT8 — from RTX 3080 · BF16 — from RTX 4090

Massed Compute hourly prices, November 2026. The discounted price applies with the coupon at checkout.

This is a LoRA: counted together with its base model Llama-3.1-8B-Instruct.

Estimate: weights plus working memory. Long videos, high resolutions and long contexts need more.

Run it on Massed Compute

A ready script for the machine we advise above: paste it and the model downloads and starts.

  1. 1. Rent A30

    $0.26 an hour with the coupon. Pick the Ubuntu image when you create the machine.

    Open Massed Compute
  2. 2. Paste the script into the machine's terminal

    Connect over SSH (the Massed Compute panel shows the command) or open a terminal on the machine's desktop.

    HF_TOKEN / CIVITAI_TOKENThe script starts with token lines: paste yours between the quotes. The Hugging Face token is for gated models, the Civitai one for Civitai models.

    # anasbiswas/Llama-3.1-8B-Instruct-TwinDistillation — A30, FP8 / INT8
    # ===== Tokens: paste yours between the quotes =====
    export HF_TOKEN=""        # huggingface.co/settings/tokens, for gated models
    # ==========================================
    # NVIDIA driver: CUDA 13 needs 580+. If older or missing, the current nvidia-open is installed (keep yours: KEEP_DRIVER=1)
    DRV=$(nvidia-smi --query-gpu=driver_version --format=csv,noheader 2>/dev/null | head -1 | cut -d. -f1)
    case "$DRV" in ""|*[!0-9]*) DRV=0 ;; esac
    if [ "$DRV" -lt 580 ] && [ -z "${KEEP_DRIVER:-}" ]; then
      . /etc/os-release && \
      curl -fsSLO "https://developer.download.nvidia.com/compute/cuda/repos/ubuntu${VERSION_ID//./}/x86_64/cuda-keyring_1.1-1_all.deb" && \
      sudo dpkg -i cuda-keyring_1.1-1_all.deb && rm -f cuda-keyring_1.1-1_all.deb && \
      sudo apt-get update && \
      sudo DEBIAN_FRONTEND=noninteractive apt-get install -y nvidia-open || \
      { echo "Could not install the NVIDIA driver: see the error above. To keep the current one, run with KEEP_DRIVER=1."; exit 1; }
      echo "NVIDIA driver updated. Reboot the machine (sudo reboot) and run this same script again."
      exit 0
    fi
    curl -LsSf https://astral.sh/uv/install.sh | sh
    source "$HOME/.local/bin/env"
    uv venv ~/vllm --python 3.12 && source ~/vllm/bin/activate
    uv pip install vllm
    vllm serve meta-llama/Llama-3.1-8B-Instruct --max-model-len 8192 --quantization fp8 --enable-lora --max-lora-rank 64 --lora-modules Llama-3.1-8B-Instruct-TwinDistillation=anasbiswas/Llama-3.1-8B-Instruct-TwinDistillation
    Add more LoRAs to Llama-3.1-8B-Instruct
  3. 3. Use it

    The server listens on port 8000 and speaks the OpenAI API: http://localhost:8000/v1 on the machine. From your computer: ssh -L 8000:localhost:8000 user@machine-IP.

Stop the machine in the panel when you are done: it bills by the minute while it runs.

How to speed it up

Picked for this model type. Choose your hardware above to see what fits you exactly.

  • FlashAttention 44.0.0b40from November 18, 2026new release

    fastest exact attention on B200

    Kernels for Blackwell (beta). Exact attention without quantisation — fine for everything, LLMs included.

    How to enable: pip install flash-attn-4; vLLM and SGLang pick it up themselves.

    Earlier generations (2)
    • FlashAttention 3 — The Hopper (H100/H200) version with FP8.
    • FlashAttention 2 — The standard for RTX 30/40/50 and A100: exact attention without the memory cost of long contexts.
  • torch.compile2.15.0from October 28, 2026new release

    10–30% for free

    Compiles the model for your GPU. Slower first run, faster afterwards.

    How to enable: model = torch.compile(model); in ComfyUI the TorchCompileModel node.

  • MTP (multi-token prediction)0.34.0from November 16, 2026new release

    1.5–2× generation speed

    If the model has MTP layers (DeepSeek-V3/R1, Qwen3-Next, GLM, MiMo and others), it predicts several tokens per step itself.

    How to enable: vLLM / SGLang: --speculative-config '{"method": "mtp", "num_speculative_tokens": 1}'. Check the model card.

    Earlier generations (2)
    • EAGLE-3 — Speculative decoding with a small draft head. For models without their own MTP layers.
    • EAGLE-2 / Medusa — Earlier draft-head generations. Still work if that is all you find.
  • FP8 KV cache0.34.0from November 16, 2026new release

    2× more context in the same memory

    Keeps the attention cache in 8 bits, so long contexts fit where they did not.

    How to enable: vLLM: --kv-cache-dtype fp8; llama.cpp: -ctk q8_0 -ctv q8_0.

  • vLLM / SGLang0.34.0from November 16, 2026new release

    many times more tokens/s on a server

    Server engines: batching, FlashAttention, FP8 and speculative decoding out of the box.

    How to enable: vllm serve <model> — an OpenAI-compatible API.

    Earlier generations (1)
    • llama.cpp — GGUF models on any GPU, Mac or even CPU; some layers can stay in RAM.

Model family

Requires the base model

meta-llama/Llama-3.1-8B-Instruct

This model is a LoRA / adapter. Download the base model first, then load this one on top.

  1. Meta-Llama-3.1-8Bfamily root
  2. Llama-3.1-8B-Instruct
  3. Llama-3.1-8B-Instruct-TwinDistillation

New posts about versions of Meta-Llama-3.1-8B (quants, finetunes, LoRAs) will show up under the bell.

No known relatives of this model yet. All derivatives on Hugging Face

About the model

anasbiswas/Llama-3.1-8B-Instruct-TwinDistillation
Author
anasbiswas
Category
Language models
Released
Posted

On NeyroLearn

Hugging Face

120

Ask AI about this model

Answered by Gemini 4 · the chat is kept only in this tab

Comments