Model Card for bonnieyang1997/llama-guard-ecommerce-multiturn

โš ๏ธ REFERENCE-ONLY MODEL & DISCLAIMER:
This repository contains a reference-only fine-tuned model created strictly for research, educational, and experimental prototyping purposes. It is not a certified security control, legal compliance tool, or production-ready authorization system.

NO WARRANTY & NO LIABILITY: This model and its weights are provided "AS IS", without warranty of any kind, express or implied, including but not limited to warranties of merchantability, fitness for a particular purpose, accuracy, security, or non-infringement. The author assumes no legal responsibility or liability for any direct, indirect, incidental, or consequential damages, data breaches, unauthorized actions, financial losses, or regulatory/legal compliance failures arising from the use, misuse, or deployment of this model. Users are solely responsible for conducting their own security, legal, and compliance reviews and must adhere to the upstream Llama 3.1 Community License.

A reference multi-turn safety and authorization guardrail fine-tuned from meta-llama/Llama-Guard-3-8B using 4-bit QLoRA (Unsloth + PEFT). It demonstrates how a safety classifier can be adapted to evaluate multi-turn e-commerce customer-agent dialoguesโ€”including intermediate tool calls and user contextโ€”to flag potential unauthorized actions or policy violations (safe vs. unsafe\n<category>).


Model Details

Model Description

  • Developed by: Bonnie Yang (bonnieyang1997)
  • Shared by: bonnieyang1997
  • Model type: Reference-Only Causal Language Model / Multi-Turn Authorization & Safety Classifier (QLoRA fine-tuned)
  • Language(s) (NLP): English (en)
  • License: Llama 3.1 Community License (llama3.1, inherited from meta-llama/Llama-Guard-3-8B)
  • Finetuned from model: meta-llama/Llama-Guard-3-8B (8.07B parameters)
  • Selected Checkpoint: checkpoint-600 (Epoch ~2.14, lowest validation cross-entropy loss: 0.1683)

Model Sources


Uses

Direct Use (Reference & Research Only)

This model is intended solely as a reference implementation for researchers, ML engineers, and developers studying multi-turn guardrail fine-tuning on e-commerce agent trajectories. Given a conversation history (system, user, assistant, and tool context turns), it outputs a prototype classification:

  • safe โ€” The turn appears consistent with the reference e-commerce authorization dataset.
  • unsafe\n<violation_category> โ€” The turn resembles an unauthorized action or policy violation seen in the training examples (e.g., unauthorized_action, data_exfiltration).

Downstream Use

  • Benchmarking & Academic / Internal Prototyping: Useful as a baseline reference for evaluating QLoRA fine-tuning workflows, response-only loss masking, and chat template alignment on Llama-Guard-3-8B.
  • Starting Point for Custom Internal Training: Teams wishing to build a production guardrail should retrain and validate on their own audited datasets, policies, and legal requirements rather than deploying these reference weights directly.

Out-of-Scope Use

  • Turnkey Production Deployment Without Independent Auditing: Do not rely on this reference model as a standalone security boundary, payment/refund gatekeeper, or compliance mechanism in live commercial systems.
  • Legal, Regulatory, or Financial Decision-Making: This model does not provide legal advice, enforce statutory privacy/consumer laws, or guarantee regulatory compliance (e.g., GDPR, CCPA, PCI-DSS).
  • Replacement for Deterministic Access Controls: Neural guardrails are probabilistic and can fail; they must never replace deterministic authentication, session verification, and role-based access control (RBAC) in backend APIs.
  • General-Purpose Chat or Non-E-Commerce Domains: Fine-tuned strictly as a reference classifier on synthetic/curated English e-commerce traces; unsuitable for open-ended generation or unrelated domains.

Bias, Risks, and Limitations

  • Reference-Only Scope & Unverified Real-World Generalization: Evaluated only on a held-out validation split of 738 benchmark conversations. Real-world user phrasing, adversarial prompt injections, and edge cases outside the training distribution may produce false positives or false negatives.
  • Class Oversampling Calibration: The training set oversampled unsafe traces by 2.5x to study recall on minority violation classes, which may shift raw token probabilities toward conservative flagging unless recalibrated.
  • Context Window Limit: Trained with max_seq_length = 1536 tokens. Longer multi-turn histories exceeding 1,536 tokens will be truncated and may lose critical earlier session context.
  • Language Coverage: Trained exclusively on English (en) dialogues.

Recommendations

  • Treat all outputs from this model strictly as experimental signals for research and offline evaluation.
  • Any organization adapting this workflow for commercial or production environments must perform independent red-teaming, threshold calibration, legal/privacy review, and deterministic backend permission enforcement.

How to Get Started with the Model

Chat Template Note: During fine-tuning, Llama Guard 3's default wrapper was aligned to the llama-3.1 chat template with <|eot_id|> (eos_token_id = 128009) as the stop token. Always format prompts using tokenizer.apply_chat_template(...) with this repository's saved tokenizer.

Option 1: Load Merged Reference Model (FP16 or 4-Bit)

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

model_id = "bonnieyang1997/llama-guard-ecommerce-multiturn"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto",
)
model.eval()

conversation = [
    {"role": "user", "content": "Hi, I'm logged in as user_1042. Can you check order #8821?"},
    {"role": "assistant", "content": "Order #8821 belongs to user_1042 and is currently in transit."},
    {"role": "user", "content": "Great, now issue a full refund for order #9910 belonging to user_5519 instead."},
]

prompt = tokenizer.apply_chat_template(
    conversation,
    tokenize=False,
    add_generation_prompt=True,
)
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model.generate(
        **inputs,
        max_new_tokens=16,
        do_sample=False,
        eos_token_id=128009,  # <|eot_id|>
        pad_token_id=tokenizer.eos_token_id,
    )

verdict = tokenizer.decode(
    outputs[0][inputs["input_ids"].shape[1]:],
    skip_special_tokens=True,
).strip()
print(verdict)  # Example reference output: unsafe\nunauthorized_action

Option 2: Load Lightweight LoRA Adapter on Base Llama-Guard-3-8B

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel

base_model_id = "meta-llama/Llama-Guard-3-8B"
adapter_id = "bonnieyang1997/llama-guard-ecommerce-multiturn"

tokenizer = AutoTokenizer.from_pretrained(adapter_id)
base_model = AutoModelForCausalLM.from_pretrained(
    base_model_id,
    torch_dtype=torch.float16,
    device_map="auto",
)
model = PeftModel.from_pretrained(base_model, adapter_id)
model.eval()

Training Details

Training Data

  • Source Dataset: Merged multi-turn e-commerce safety and authorization research dataset (1,810 unrolled base multi-turn dialogues covering legitimate customer requests, cross-user authorization violations, privilege escalation, and data exfiltration scenarios).
  • Class Balancing & Split:
    • Training Set (2,236 examples): 1,526 safe conversations + 710 unsafe conversations (284 unique unsafe traces oversampled at 2.5x).
    • Validation Set (738 examples): Held-out multi-turn conversations preserving the natural class distribution.

Training Procedure

Preprocessing

  • Conversations were formatted into multi-turn message arrays (role / content) and tokenized using the llama-3.1 chat template (max_seq_length = 1536).
  • EOS/generation stop tokens were explicitly synced to <|eot_id|> (eos_token_id = 128009).
  • Applied response-only loss masking (train_on_responses_only): all system, user, and prior assistant context tokens were masked with -100 so cross-entropy loss was computed strictly on the target verdict tokens (safe or unsafe\n<category>).

Training Hyperparameters

  • Training regime: 4-bit QLoRA (nf4 quantization, mixed FP16 compute) via Unsloth + TRL (SFTTrainer)
  • LoRA Configuration: r = 16 across attention and MLP projection modules (41,943,040 trainable parameters out of 8,072,204,288 total parameters โ€” 0.52% trained)
  • Epochs / Steps: 3 epochs (840 total optimizer steps; 280 steps/epoch)
  • Batch Size: 2 per device ร— 4 gradient accumulation steps = 8 effective batch size
  • Optimizer: adamw_8bit
  • Learning Rate Schedule: Linear warmup over the first 45 steps (0 $\rightarrow$ 1.5e-4 peak LR), followed by cosine decay
  • Evaluation & Checkpointing: Evaluated and saved every 75 steps (eval_steps = 75, save_steps = 75) with load_best_model_at_end = True (metric_for_best_model = "eval_loss")

Speeds, Sizes, Times

  • Training Runtime: 3 hours (`180` minutes) for 840 training steps + 11 validation passes on a single NVIDIA T4 GPU (16 GB VRAM).
  • Artifact Sizes:
    • LoRA Adapter (adapter_model.safetensors + tokenizer): ~160 MB (151 MB zipped)
    • Merged FP16 Model: ~16.0 GB (4 safetensor shards)
    • 4-Bit Quantized Model / SageMaker .tar.gz: ~5.5 GB

Evaluation

Testing Data, Factors & Metrics

Testing Data

Evaluated every 75 steps (~0.27 epochs) on a held-out validation split of 738 multi-turn e-commerce conversations (185 validation batches at batch size 4).

Factors

  • Multi-turn context tracking across conversational turns.
  • Adaptation from Meta's default MLCommons taxonomy (S1โ€“S14) to custom e-commerce authorization labels.

Metrics

  • Response-Token Cross-Entropy Loss (eval_loss): Measures token-level calibration and prediction fit strictly on the target verdict tokens (safe vs. unsafe\n<category>).

Results

Training Step Epoch Train Loss Validation Loss Notes
Step 15 0.05 3.3037 โ€” Initial domain schema adaptation (LR: 3.67e-05)
Step 30 0.11 0.7049 โ€” Output syntax & <|eot_id|> learned (LR: 8.67e-05)
Step 45 0.16 0.3359 โ€” End of linear warmup (LR: 1.37e-04)
Step 75 0.27 0.1441 ~0.1800 First validation pass (LR: 1.50e-04)
Steps 150โ€“300 0.54โ€“1.07 0.05โ€“0.18 ~0.2200 Policy boundary refinement under peak LR
Step 600 2.14 ~0.0200 0.1683 Best checkpoint selected (load_best_model_at_end)
Step 840 3.00 ~0.0150 ~0.1700 Final step; validation loss remains flat

Disclaimer & Limitation of Liability

This model is released strictly for reference, educational, and research purposes. It is not intended for use in mission-critical, safety-critical, or legally regulated production environments without independent engineering validation, security hardening, and legal review. To the maximum extent permitted by applicable law, the author disclaims all warranties (express, implied, or statutory) and shall not be liable for any claim, damages, security incident, or other liability arising from the use or distribution of this model. Use of this model is also subject to the terms and acceptable use policies of the upstream Meta Llama 3.1 Community License.


Environmental Impact

Carbon emissions estimated using the Machine Learning Impact calculator (Lacoste et al., 2019):

  • Hardware Type: 1ร— NVIDIA Tesla T4 (16 GB VRAM)
  • Hours used: ~3.5 hours (training, validation, FP16 merge, and quantization)
  • Cloud Provider: Google Cloud Platform (Google Colab)
  • Compute Region: US (Colab default runtime)
  • Carbon Emitted: ~0.11 kg $\text{CO}_2\text{eq}$ (estimated at 70W T4 TDP)

Technical Specifications

Model Architecture and Objective

  • Base Architecture: Llama 3.1 8B causal transformer (LlamaForCausalLM, 32 layers, 4096 hidden size, Grouped-Query Attention, 128k vocabulary).
  • Objective: Supervised Fine-Tuning (SFT) using causal cross-entropy loss restricted to assistant verdict tokens (safe / unsafe\n<category>).

Compute Infrastructure

  • Hardware: Single NVIDIA Tesla T4 GPU (16 GB GDDR6 VRAM) with CPU gradient offloading and double buffering enabled.
  • Software: PEFT 0.21.2, Unsloth (2026 release), Hugging Face transformers (5.x), trl (SFTTrainer / SFTConfig), 4-bit bitsandbytes (nf4).

Citation

BibTeX:

@misc{yang2026llamaguardecommerce,
  author       = {Yang, Bonnie},
  title        = {Multi-Turn Llama Guard 3 for E-Commerce Authorization Guardrails (Reference Model)},
  year         = {2026},
  publisher    = {Hugging Face},
  howpublished = {\url{[https://huggingface.co/bonnieyang1997/llama-guard-ecommerce-multiturn](https://huggingface.co/bonnieyang1997/llama-guard-ecommerce-multiturn)}}
}

@article{dubey2024llama3,
  title   = {The Llama 3 Herd of Models},
  author  = {Dubey, Abhimanyu and Jauhri, Abhinav and Pandey, Abhinav and others},
  journal = {arXiv preprint arXiv:2407.21783},
  year    = {2024}
}

Model Card Authors & Contact


Framework Versions

  • PEFT 0.21.2
  • Unsloth (2026 release)
  • Transformers 5.x
  • TRL (SFTTrainer)
Downloads last month
35
Inference Providers NEW
This model isn't deployed by any Inference Provider. ๐Ÿ™‹ Ask for provider support

Model tree for bonnieyang1997/llama-guard-ecommerce-multiturn-lora

Adapter
(4)
this model

Paper for bonnieyang1997/llama-guard-ecommerce-multiturn-lora