Meta logo

Llama Guard 4 12B

Llamav4 12BCurrent
byMetaMeta(technology company)
Released April 30, 2025
Context163.8K tokens
Price (In / Out)$0.18/M / $0.18/M
CategoryMultimodal LLM
Max Output40 tokens

About Llama Guard 4 12B

Llama Guard 4 12B is a Meta multimodal safety-classification model for text and image prompt or response moderation using MLCommons hazard categories.

Capabilities

textvisioncode

Input Modalities

imagetext

Output Modalities

text

Technical Details

API Identifier
meta-llama/llama-guard-4-12b
Category
Multimodal LLM
Context Window
163,840 tokens
Max Output Tokens
40 tokens

Tags

multimodalbudget-friendlylong-contextsafetymoderationguardrails

Run this model yourself

Local and cloud setup for Llama Guard 4 12B, with exact configurations, sources and clear evidence limits.

Find a model for your hardware
Local hardwareDocumented setupSources checked Oct 16, 2026

Run Llama Guard 4 text input classification on a 64 GiB Intel desktop

Classify one text input using the exact public Unsloth Llama Guard 4 snapshot, Meta classification template and native dense Transformers CPU FP32 path. A reader-authored private endpoint returns safe/unsafe and 14-category labels. One request, 4,096 total tokens and a 32-token greedy check. Fit, speed and classifier accuracy remain unmeasured.

Hardware
Intel Core i5-12400 desktop, 8 inference threads, 64 GiB RAM
Runtime
Native dense Llama Guard 4 CPU classifier with reader-authored private endpoint Python 3.12; Torch 2.6.0+cpu; TorchVision 0.21.0+cpu; Transformers 4.57.6; FP32 eager attention · CPU
Model format
safetensors · Full native BF16 artifact explicitly loaded as CPU FP32 · No quantization; original BF16 snapshot converted to FP32 on CPU
Workload
4,096 token context · 1 concurrent

Based on source documentation; this setup has not been executed by OpenTools. Memory: unknown. No compatible measurement available.

Read the complete setup guide

Before you start

  • Use an owned Intel Core i5-12400 Ubuntu 24.04 x86_64 desktop with 64 GiB RAM, 80 GiB free disk and eight allocated inference threads.
  • Use the exact independently public Unsloth snapshot, native Meta classifier template and pinned CPU Python packages. Meta raw checkpoint files remain manually gated; no credential, native download approval or exact byte equivalence is inferred.
  • Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.
  • The fixed single-user text input classifier is not a general assistant or a guarantee that content is safe. Model labels can be wrong; evaluate your intended policy/workload before relying on results.

Exact model and requirements

Artifact:
Unsloth (public snapshot); Meta (native classifier) / Public Unsloth Llama-Guard-4-12B full five-shard BF16 snapshot · checkpoint unsloth/Llama-Guard-4-12B
Publisher revision:
07ebbb7bdc44fb45bf710a9a69a82c088085f0c8
Artifact digest:
No publisher single-file digest for this multi-file snapshot. Mandatory recipe verifies all five weight SHA256s and every required auxiliary; no index hash is called a whole-weight digest.
Download size:
22.35 GiB
Memory requirement (unknown):
Unknown — No measured full CPU peak for this 12B dense model loaded FP32, native vision encoder and 4K bounded classifier workload.
System RAM / disk:
Unknown / Unknown
Placement:
single device. One CPU host, no tensor or pipeline sharding. Entire dense text model, integrated vision encoder and projector stay on CPU. No GPU, disk offload, device_map or active-expert weight reduction.
KV cache:
FP32 native attention K/V with author-selected dynamic cache
Workload:
4,096 token context; Unknown; Unknown; concurrency 1; batch 1; cache unknown; repetitions Unknown.
Tokenizer:
Pinned public Llama Guard 4 tokenizer plus Meta classifier template from revision API · Public Unsloth snapshot and Meta native classifier template, independently pinned in artifacts and download steps
Sampling / reasoning:
Greedy do_sample=False; author max_new_tokens 32 and repetition_penalty 1.0. Native generation config supplies EOS IDs and pad token. Dynamic rather than native static cache avoids allocating the architectural maximum; actual memory remains unknown. Safety classifier generates label text, not chat answers or free reasoning. Fixed native policy: 14 text categories S1–S14. One user input only; system/assistant history, response filtering, category customization and tool execution are not implemented.
Runtime prerequisites:
Ubuntu 24.04 x86_64; See prerequisites above.

Official artifact · License

Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.

  • All 24,002,322,024 original weight bytes load. FP32 doubles BF16 weight storage in memory before cache, compute/vision buffers and OS; exact startup and peak remain unknown.
  • The classifier is dense after pruning; no Scout routed-expert or active-parameter memory discount applies. 64 GiB RAM, 80 GiB disk and eight threads are planning allocations, not confirmed fit/minima.

One-time setup and hardware

hardware
Unknown — Existing desktop purchase price and incremental hardware cost depend on the reader; unknown.
Existing desktop purchase price and incremental hardware cost depend on the reader; unknown. Tax: unknown.
setup
Unknown — Initial provisioning/build time and labor cost are unknown.
Initial provisioning/build time and labor cost are unknown. Tax: unknown.

Recurring costs

electricity
Unknown — Actual wall power, electricity rate and powered hours are unknown; no TDP-to-wall-power conversion.
Actual wall power, electricity rate and powered hours are unknown; no TDP-to-wall-power conversion. Tax: unknown.
storage
Unknown — Incremental cost of local disk capacity is unknown. The 80 GiB free-disk walkthrough allocation is an author choice, not a measured requirement.
Incremental cost of local disk capacity is unknown. The 80 GiB free-disk walkthrough allocation is an author choice, not a measured requirement. Tax: unknown.
egress
Unknown — Data transfer price, allowances and traffic volume are unknown.
Data transfer price, allowances and traffic volume are unknown. Tax: unknown.
administration
Unknown — Maintenance labor rate and hours are unknown.
Maintenance labor rate and hours are unknown. Tax: unknown.

Install the runtime

  1. 1. Create the exact CPU package environment

    Use the official hash-pinned Torch/TorchVision CPU wheels and native Transformers release. TorchVision supports the native fast image processor, including when a text-only model loads its processor. Transitive/system packages resolve at installation; save versions and stop on conflicts. No installation was executed by the author.

    Command
    sudo apt-get update
    sudo apt-get install -y python3.12 python3.12-venv curl ca-certificates openssl
    mkdir -p "$HOME/llama-guard4-hosting/model"
    cd "$HOME/llama-guard4-hosting"
    python3.12 -m venv .venv
    .venv/bin/python -m pip install 'https://download.pytorch.org/whl/cpu/torch-2.6.0%2Bcpu-cp312-cp312-linux_x86_64.whl#sha256=59e78aa0c690f70734e42670036d6b541930b8eabbaa18d94e090abf14cc4d91' 'https://download-r2.pytorch.org/whl/cpu/torchvision-0.21.0%2Bcpu-cp312-cp312-linux_x86_64.whl#sha256=d6874431e678ba107b60a83f255c33f3755f06bad587b1b919aa514ec325dcd8'
    .venv/bin/python -m pip install 'transformers==4.57.6' pillow
    .venv/bin/python -m pip check
    .venv/bin/python -m pip freeze > resolved-environment.txt

    Expected result: pip hash checks and pip check pass; actual environment is recorded. No CUDA driver or remote model code is used.

Download the model

  1. 1. Download and verify all original derivative weight shards

    Fetch the complete public Unsloth artifact, not gated Meta weight URLs. Verify exact sizes and SHA256s. Existing valid files are reused; partial files cannot replace final files before verification.

    Command
    cd "$HOME/llama-guard4-hosting"
    .venv/bin/python - <<'PYDOWNLOAD'
    import pathlib,json,urllib.request,hashlib
    manifest=json.loads("{\"model-00001-of-00005.safetensors\":{\"bytes\":4997861792,\"sha256\":\"1b3e93a5c09f732537068482a5f00c29a675092f0ae456ebd60043af59c21299\"},\"model-00002-of-00005.safetensors\":{\"bytes\":4981018296,\"sha256\":\"08150644f6be3ae2474a8a9f3290edbc62ac876522217c6bf70ce304ed1351e2\"},\"model-00003-of-00005.safetensors\":{\"bytes\":4991503856,\"sha256\":\"1d30c028733fc776ac18a369d565bb395fa4473aa2317cbedeef1cd216c6b327\"},\"model-00004-of-00005.safetensors\":{\"bytes\":4991503856,\"sha256\":\"ecd9fed60f059359941913c3ade611e8c67a63ba453efbc071de8af007c586e7\"},\"model-00005-of-00005.safetensors\":{\"bytes\":4040434224,\"sha256\":\"57aa2d6a20feb15010f74599e4a4f9f4985cb1b87a975dc6ffc1d34780de7599\"}}")
    for name,meta in manifest.items():
     path=pathlib.Path('model')/name
     def valid(p):
      if not p.exists() or p.stat().st_size!=meta['bytes']:return False
      h=hashlib.sha256()
      with p.open('rb') as f:
       for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
      return h.hexdigest()==meta['sha256']
     if not valid(path):
      tmp=path.with_name(path.name+'.partial')
      with urllib.request.urlopen('https://huggingface.co/unsloth/Llama-Guard-4-12B/resolve/07ebbb7bdc44fb45bf710a9a69a82c088085f0c8/'+name) as response,tmp.open('wb') as out:
       while True:
        b=response.read(8*1024*1024)
        if not b:break
        out.write(b)
      assert valid(tmp),name+' hash/size mismatch';tmp.replace(path)
     assert valid(path);print(name,'OK')
    PYDOWNLOAD

    Expected result: All five original weight shards report OK; total weight bytes 24,002,322,024. No model loads.

  2. 2. Download every required config, tokenizer, processor and license file

    Every required auxiliary is pinned. The independently published Unsloth template adds a BOS prefix; do not use it. The next step extracts the original Meta template from the public metadata API instead.

    Command
    cd "$HOME/llama-guard4-hosting"
    .venv/bin/python - <<'PYDOWNLOAD'
    import pathlib,json,urllib.request,hashlib
    manifest=json.loads("{\"LICENSE\":{\"bytes\":7554,\"sha256\":\"73755cee886613ae3135140882289e0a4955d5f0e90f8b1c1ffc962aa9082917\"},\"USE_POLICY.md\":{\"bytes\":5796,\"sha256\":\"5ae40fe842b87b5773c47cfd25992a496cc09b17cbb246968762f06352d89270\"},\"config.json\":{\"bytes\":2789,\"sha256\":\"344ab345ed1268f17e1d6f7d8eb3947b56ac90ca28834c18c171b64a026563cc\"},\"generation_config.json\":{\"bytes\":222,\"sha256\":\"edf659fdf486cfa5eb4cf127cac2dbac0f24f69439051f5111c66d72e47c31df\"},\"model.safetensors.index.json\":{\"bytes\":95229,\"sha256\":\"cdcb8ad59ccafa69c79df8cd9f109453293c613241dd03e216df01f19538dacd\"},\"preprocessor_config.json\":{\"bytes\":636,\"sha256\":\"11a1b41f43161e324bf8302299bce8d59aba671d1505137d9d01179ae9aeacde\"},\"processor_config.json\":{\"bytes\":128,\"sha256\":\"bfc23f929e2a90ba534426072b2e0288909820f34ae79d8ff3934edda29e1f3a\"},\"special_tokens_map.json\":{\"bytes\":451,\"sha256\":\"3484f80da421ad864f1646dd563b8b772ebc9666c34a19d199d6d481c96d1eda\"},\"tokenizer.json\":{\"bytes\":27948580,\"sha256\":\"22e009b4fcb58eddbabf347e71b9881ea1e6eb72d44e5ea9477c7587df68fd8d\"},\"tokenizer_config.json\":{\"bytes\":235854,\"sha256\":\"13bb887373efca2fea1225d3051500e7b0b215824eeaa5d0ba7c2ce85985ff7f\"}}")
    for name,meta in manifest.items():
     path=pathlib.Path('model')/name
     def valid(p):
      if not p.exists() or p.stat().st_size!=meta['bytes']:return False
      h=hashlib.sha256()
      with p.open('rb') as f:
       for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
      return h.hexdigest()==meta['sha256']
     if not valid(path):
      tmp=path.with_name(path.name+'.partial')
      with urllib.request.urlopen('https://huggingface.co/unsloth/Llama-Guard-4-12B/resolve/07ebbb7bdc44fb45bf710a9a69a82c088085f0c8/'+name) as response,tmp.open('wb') as out:
       while True:
        b=response.read(8*1024*1024)
        if not b:break
        out.write(b)
      assert valid(tmp),name+' hash/size mismatch';tmp.replace(path)
     assert valid(path);print(name,'OK')
    PYDOWNLOAD

    Expected result: All ten native-format derivative auxiliaries report OK. No generic Guard 3/Scout template is substituted.

  3. 3. Extract and verify the native Meta classifier template

    The raw native template is gated, but this revision-specific public API exposes its exact string. Verify the full minimal API response bytes, assert the native revision, encode the template string unchanged and verify its derived digest. The API request expands only immutable sha/config fields, avoiding live download counters.

    Command
    cd "$HOME/llama-guard4-hosting"
    curl --fail --location --output native-template-api.json 'https://huggingface.co/api/models/meta-llama/Llama-Guard-4-12B/revision/87acb4b94e930c3d679e6e7ee9d57e2feab9ea71?expand%5B%5D=sha&expand%5B%5D=config'
    sha256sum --check <<'SHA256'
    08b0234e5e3fdd5efb6abfd32d52840eba4b439bba0b11f203df5eea95d08c80  native-template-api.json
    SHA256
    .venv/bin/python - <<'PYTEMPLATE'
    import pathlib,json,hashlib
    meta=json.loads(pathlib.Path('native-template-api.json').read_text())
    assert meta['sha']=='87acb4b94e930c3d679e6e7ee9d57e2feab9ea71'
    raw=meta['config']['chat_template_jinja'].encode('utf-8')
    assert hashlib.sha256(raw).hexdigest()=='40782d45db7ce0d96b0b2595c698e47603e2d459b0390f5025d974c861c53e3b'
    pathlib.Path('native-chat.jinja').write_bytes(raw)
    assert pathlib.Path('native-chat.jinja').read_bytes()==meta['config']['chat_template_jinja'].encode('utf-8')
    print('Native classifier template extracted verbatim and verified')
    PYTEMPLATE

    Expected result: API file reports OK and native template derivation passes. Exactly one template BOS is used with add_special_tokens=False; no Unsloth extra BOS is added.

Configure

  1. 1. Preserve a private service credential

    Generate a local service key only when absent. Keep it private; this is not a provider credential. An empty existing key must be restored, not silently rotated.

    Command
    cd "$HOME/llama-guard4-hosting"
    umask 077
    if [ ! -e .api-key ]; then openssl rand -hex 32 > .api-key; fi
    test -s .api-key || { echo 'Restore empty key before proceeding'; exit 1; }
    chmod 600 .api-key

    Expected result: A nonempty mode600 key exists; no secret is printed.

  2. 2. Write the private classifier wrapper

    This reader-authored serial HTTPServer implements the documented fixed classifier workflow, not an official Meta server. Native eager attention and dense-layer assertions avoid treating the pruned model as Scout MoE. It checks actual full policy/image token count before generating, and validates native labels without converting invalid output to safe.

    Command
    cd "$HOME/llama-guard4-hosting"
    cat > guard_server.py <<'PYSERVER'
    """Reader-authored private educational classifier, not an official Meta server."""
    import base64,hmac,io,json,os,re
    from http.server import BaseHTTPRequestHandler,HTTPServer
    
    def check_budget(count,limit):
        if count>4032 or count+limit>4096: raise ValueError('input_or_budget')
    
    def parse_label(raw,image_mode):
        raw=raw.strip()
        if raw=='safe': return {'label':'safe','categories':[]}
        match=re.fullmatch(r'unsafe\s*\n\s*(S[0-9]+(?:\s*,\s*S[0-9]+)*)',raw)
        if not match: raise ValueError('invalid_classifier_output')
        keys=[x.strip() for x in match[1].split(',')]
        if len(set(keys))!=len(keys) or any(k not in {'S'+str(i) for i in range(1,14 if image_mode else 15)} for k in keys): raise ValueError('invalid_classifier_output')
        return {'label':'unsafe','categories':keys}
    
    def handler_factory(generate,key,image_mode):
        class Handler(BaseHTTPRequestHandler):
            protocol_version='HTTP/1.0'
            def setup(self):
                super().setup();self.connection.settimeout(10)
            def log_message(self,*args): pass
            def reply(self,status,data):
                body=json.dumps(data,ensure_ascii=False).encode();self.send_response(status)
                self.send_header('Content-Type','application/json; charset=utf-8');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
            def auth(self): return hmac.compare_digest(self.headers.get('Authorization','').encode(),('Bearer '+key).encode())
            def do_GET(self):
                if not self.auth(): return self.reply(401,{'error':'unauthorized'})
                self.reply(200,{'status':'ready'}) if self.path=='/health' else self.reply(404,{'error':'not_found'})
            def do_POST(self):
                if not self.auth(): return self.reply(401,{'error':'unauthorized'})
                if self.path!='/v1/guard': return self.reply(404,{'error':'not_found'})
                if self.headers.get('Transfer-Encoding') is not None: return self.reply(400,{'error':'unsupported_transfer_encoding'})
                if self.headers.get_content_type()!='application/json': return self.reply(415,{'error':'json_required'})
                lengths=self.headers.get_all('Content-Length',[])
                if len(lengths)!=1 or not lengths[0] or not all('0'<=c<='9' for c in lengths[0]): return self.reply(411,{'error':'content_length_required'})
                if len(lengths[0])>6: return self.reply(413,{'error':'body_limit'})
                n=int(lengths[0])
                if not 1<=n<=360000: return self.reply(413,{'error':'body_limit'})
                try:
                    raw=self.rfile.read(n)
                    if len(raw)!=n: return self.reply(400,{'error':'incomplete_body'})
                    data=json.loads(raw)
                except (ValueError,UnicodeError,TimeoutError): return self.reply(400,{'error':'invalid_json'})
                fields={'text','max_new_tokens'}|({'image_base64'} if image_mode else set())
                if type(data)!=dict or set(data)!=fields: return self.reply(400,{'error':'invalid_fields'})
                if type(data['text'])!=str or not data['text'].strip() or type(data['max_new_tokens'])!=int or not 1<=data['max_new_tokens']<=64: return self.reply(400,{'error':'invalid_fields'})
                try: text_size=len(data['text'].encode('utf-8'))
                except UnicodeError: return self.reply(400,{'error':'invalid_text'})
                if text_size>2048: return self.reply(400,{'error':'invalid_text'})
                image=None
                if image_mode:
                    if type(data['image_base64'])!=str or len(data['image_base64'])>349528: return self.reply(400,{'error':'invalid_image'})
                    try: image=base64.b64decode(data['image_base64'],validate=True)
                    except ValueError: return self.reply(400,{'error':'invalid_image'})
                    if not 1<=len(image)<=262144: return self.reply(400,{'error':'invalid_image'})
                try: result=generate(data['text'],data['max_new_tokens'],image)
                except ValueError: return self.reply(422,{'error':'input_budget_or_classifier_format'})
                except Exception: return self.reply(500,{'error':'classification_failed'})
                self.reply(200,result)
        return Handler
    
    def main():
        import warnings,torch
        from PIL import Image
        from transformers import AutoProcessor,Llama4ForConditionalGeneration
        image_mode=os.environ.get('GUARD_IMAGE_MODE')=='1'
        key=open('.api-key').read().strip()
        if len(key)!=64 or any(c not in '0123456789abcdef' for c in key): raise SystemExit('Invalid private key')
        torch.set_num_threads(8)
        processor=AutoProcessor.from_pretrained('./model',local_files_only=True,trust_remote_code=False)
        processor.chat_template=open('native-chat.jinja').read()
        model=Llama4ForConditionalGeneration.from_pretrained('./model',local_files_only=True,trust_remote_code=False,dtype=torch.float32,attn_implementation='eager').to('cpu').eval()
        cfg=model.config.text_config
        assert cfg.moe_layers==[] and cfg.num_local_experts==0 and cfg.num_hidden_layers==48 and cfg.hidden_size==5120
        assert all(not layer.is_moe_layer for layer in model.language_model.model.layers)
        assert next(model.parameters()).dtype==torch.float32
        Image.MAX_IMAGE_PIXELS=4194304
        warnings.simplefilter('error',Image.DecompressionBombWarning)
        def generate(text,limit,image):
            content=[];images=None
            if image is not None:
                try:
                    with Image.open(io.BytesIO(image)) as source:
                        if source.format not in ('PNG','JPEG') or not 1<=source.width<=2048 or not 1<=source.height<=2048: raise ValueError('image_bounds')
                        images=[source.convert('RGB')]
                except (OSError,Image.DecompressionBombError,Image.DecompressionBombWarning) as error: raise ValueError('image_decode') from error
                content.append({'type':'image'})
            content.append({'type':'text','text':text})
            prompt=processor.apply_chat_template([{'role':'user','content':content}],tokenize=False,add_generation_prompt=True,excluded_category_keys=[])
            inputs=processor(text=[prompt],images=images,max_patches=1,add_special_tokens=False,return_tensors='pt')
            count=inputs['input_ids'].shape[-1];check_budget(count,limit)
            assert inputs['input_ids'][0,0].item()==processor.tokenizer.bos_token_id
            with torch.inference_mode():
                out=model.generate(**inputs,max_new_tokens=limit,do_sample=False,repetition_penalty=1.0,cache_implementation='dynamic',pad_token_id=processor.tokenizer.pad_token_id)
            new=out[0,count:];raw=processor.tokenizer.decode(new,skip_special_tokens=True).strip()
            parsed=parse_label(raw,image_mode)
            if len(new)==limit: raise ValueError('classifier_output_cap')
            return {**parsed,'raw_label':raw,'input_tokens':count,'output_tokens':len(new),'policy_categories':13 if image_mode else 14}
        HTTPServer(('127.0.0.1',8996),handler_factory(generate,key,image_mode)).serve_forever()
    if __name__=='__main__': main()
    PYSERVER
    .venv/bin/python -m py_compile guard_server.py

    Expected result: Syntax check succeeds. Wrapper bytes match the source shown; py_compile does not import the model.

Start the model

  1. 1. Start the text-only input classifier

    Run in a foreground terminal. Loads all local weights and integrated vision components in CPU FP32 with eager attention. The exact native template replaces processor defaults. One sequence is served at a time; no generation deadline or public-server resilience is claimed.

    Command
    cd "$HOME/llama-guard4-hosting"
    GUARD_IMAGE_MODE=0 .venv/bin/python guard_server.py

    Expected result: After successful startup, authenticated health reports ready. Stop on model/tokenizer/dense-layer/import/RAM errors. Actual startup has not been executed here.

Connect to your endpoint

http://127.0.0.1:8996/v1/guard

Same desktop loopback only, trusted private host.

Access: loopback. Reader-generated Bearer key protects health and classifier routes. Request fields are text and max_new_tokens; image_base64 is rejected in text mode. Response fields are label, categories, raw_label, input_tokens, output_tokens and policy_categories. No chat roles, arbitrary URL fetching or provider API is exposed.

Verify the setup

  1. 1. Verify readiness, native label response and authentication

    Run in a second terminal on the same desktop or VM SSH shell. The benign greeting is expected to classify safe under the fixed text policy. This is a reader pass criterion, not an observed classifier result, calibrated score or safety guarantee. The endpoint returns labels rather than answering the greeting. Accept a complete parsed label only; invalid/empty output, cap exhaustion, context error or unexpected category fails this check.

    Command
    cd "$HOME/llama-guard4-hosting"
    printf '%s\n' '{"text":"Hello! I hope you have a nice day.","max_new_tokens":32}' > guard-request.json
    GUARD_SERVICE_KEY="$(cat .api-key)"
    curl --fail http://127.0.0.1:8996/health -H "Authorization: Bearer $GUARD_SERVICE_KEY"
    curl --fail http://127.0.0.1:8996/v1/guard -H "Authorization: Bearer $GUARD_SERVICE_KEY" -H 'Content-Type: application/json' --data-binary @guard-request.json --output guard-response.json
    cat guard-response.json
    .venv/bin/python - <<'PYRESULT'
    import json
    r=json.load(open('guard-response.json'))
    assert r['label']=='safe' and r['categories']==[] and r['policy_categories']==14
    assert 1<=r['output_tokens']<32 and r['input_tokens']+r['output_tokens']<=4096
    print('Expected native safe label and token-budget checks passed; not a general safety guarantee')
    PYRESULT
    curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8996/health
    unset GUARD_SERVICE_KEY

    Expected result: Authorized health returns ready; classification returns safe, empty categories and native policy count 14. Missing key returns401. Exact raw label text/token counts are unknown; no inference result is claimed.

Performance evidence

No compatible measurement available. Documented support and estimated memory do not establish response speed.

Limits and troubleshooting

  • Documented only: no weights, packages, model imports, installation, build or inference executed. Full fit, latency, throughput and classifier accuracy remain unknown.
  • Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.
  • The public derivative has the same five shard sizes as the gated native listing, but native LFS digests are redacted. That does not establish byte equivalence or an exact upstream conversion revision. All runnable derivative bytes are pinned independently.
  • The exact native policy template is extracted from a revision-specific public API; its full API bytes and derived UTF-8 string are verified. Mirror template adds an extra BOS prefix and is deliberately not used. add_special_tokens=False prevents automatic extra BOS.
  • Native Guard4 is dense after pruning:48 layers, hidden5120,40Q/8KV heads, no routed experts, empty moe_layers. Transformers uses a dense MLP path; eager attention is explicitly selected for text and vision. No Guard3 or generic Scout runtime behavior is assumed.
  • Fixed native template has13 image categories and14 text categories; S14 Code Interpreter Abuse is text-only. Parser rejects unexpected/duplicate category IDs, invalid/empty labels and cap exhaustion. A valid format does not establish a correct prediction.
  • Only one user input is classified. Response classification, multi-turn parity/assistant history, category customization, multilingual performance, multi-image inputs, full context and other runtimes/devices remain separate unqualified useful scopes.
  • The reader-authored endpoint is serial and private: authenticated health/classification,360000-byte body limit, strict fields/types,10-second socket read timeout, at most2048 UTF-8 text bytes, actual full input<=4032 and input+requested output<=4096. Requests allow1–64 new tokens; smoke uses32. No generation timeout, TLS/public hardening or calibrated probability is provided.
  • Image mode accepts one validated-base64 PNG/JPEG up to262144 decoded bytes and2048 by2048 pixels. Native max_patches1 resizes to one336-square tile; actual rendered policy/image/text tokens are checked before generation. Text mode accepts no image field.
  • Full FP32 weights, vision components, cache, buffers and OS share system RAM.64 GiB RAM,80 GiB disk and eight threads are allocations, not measured minima or confirmed fit.
  • Guard4 labels can have false positives and false negatives, and policy alignment may differ from your intended use. A safe label is not a universal assurance; the narrow benign fixture is not a quality benchmark.
  • System and transitive packages resolve at installation. Exact Torch/TorchVision wheel hashes and Transformers version are supplied, but target Python3.12 model/processor startup compatibility remains unexecuted.
  • Two modality pairs do not establish exhaustive model coverage. Original cloud quote dates and unknown egress/tax/admin are retained; local purchase/power remain unknown.
401 or connection refused
Check foreground startup and matching private key. For cloud check existing SSH tunnel and keep public8996 closed.
400,411,413,415 or422 response
Use exact mode-specific fields, JSON media type, one ASCII Content-Length and bounded text/image bytes. Check actual policy+image input tokens and requested generation cap. Invalid native label/category or exhausted cap is a failed classification, never an automatic safe result.
Unexpected label or category
Inspect raw_label and the native fixed policy. S14 exists only for text. Record false positive/negative behavior; do not reinterpret model labels as guaranteed safe or substitute general chat output.
Model/tokenizer/dense assertion or memory error
Stop. Verify all independent derivative hashes, native API/template derivation and exact CPU packages. Do not substitute Guard3, enable routed Scout experts, remove required assertions or silently change resource/precision.

Stop the model

  1. 1. Stop classifier and tunnel

    Press Ctrl+C in the foreground Python terminal. Unset client keys; confirm loopback8996 no longer serves.

    Command
    unset GUARD_SERVICE_KEY

    Expected result: Foreground service stops and loopback8996 no longer responds.

Uninstall

  1. 1. Remove dedicated files

    After confirming the path and preserving wanted diagnostics, remove only this walkthrough directory. Shared apt packages remain.

    Command
    rm -r -- "$HOME/llama-guard4-hosting"

    Expected result: Dedicated weights, venv, wrapper, template/API metadata, requests/responses and private key are removed.

Sources and verification

Sources checked Oct 16, 2026. Verification source

Compare this configuration
Cloud serverDocumented setupSources checked Oct 16, 2026

Self-host Llama Guard 4 text input classification on an AWS CPU VM

Classify one text input using the exact public Unsloth Llama Guard 4 snapshot, Meta classification template and native dense Transformers CPU FP32 path. A reader-authored private endpoint returns safe/unsafe and 14-category labels. One request, 4,096 total tokens and a 32-token greedy check. Fit, speed and classifier accuracy remain unmeasured.

Hardware
AWS r7i.2xlarge, 64 GiB RAM, Ubuntu x86_64
Runtime
Native dense Llama Guard 4 CPU classifier with reader-authored private endpoint Python 3.12; Torch 2.6.0+cpu; TorchVision 0.21.0+cpu; Transformers 4.57.6; FP32 eager attention · CPU
Model format
safetensors · Full native BF16 artifact explicitly loaded as CPU FP32 · No quantization; original BF16 snapshot converted to FP32 on CPU
Workload
4,096 token context · 1 concurrent

Based on source documentation; this setup has not been executed by OpenTools. Memory: unknown. No compatible measurement available.

Read the complete setup guide

Before you start

  • Use an existing authorized Ubuntu 24.04 x86_64 r7i.2xlarge in us-east-1: eight vCPUs, 64 GiB RAM and an 80 GiB gp3 root disk. Existing SSH must restrict port 22 to your IP; keep public 8996 closed. Confirm current quote, quota and capacity before billable provisioning.
  • Use the exact independently public Unsloth snapshot, native Meta classifier template and pinned CPU Python packages. Meta raw checkpoint files remain manually gated; no credential, native download approval or exact byte equivalence is inferred.
  • Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.
  • The fixed single-user text input classifier is not a general assistant or a guarantee that content is safe. Model labels can be wrong; evaluate your intended policy/workload before relying on results.

Exact model and requirements

Artifact:
Unsloth (public snapshot); Meta (native classifier) / Public Unsloth Llama-Guard-4-12B full five-shard BF16 snapshot · checkpoint unsloth/Llama-Guard-4-12B
Publisher revision:
07ebbb7bdc44fb45bf710a9a69a82c088085f0c8
Artifact digest:
No publisher single-file digest for this multi-file snapshot. Mandatory recipe verifies all five weight SHA256s and every required auxiliary; no index hash is called a whole-weight digest.
Download size:
22.35 GiB
Memory requirement (unknown):
Unknown — No measured full CPU peak for this 12B dense model loaded FP32, native vision encoder and 4K bounded classifier workload.
System RAM / disk:
Unknown / Unknown
Placement:
single device. One CPU host, no tensor or pipeline sharding. Entire dense text model, integrated vision encoder and projector stay on CPU. No GPU, disk offload, device_map or active-expert weight reduction.
KV cache:
FP32 native attention K/V with author-selected dynamic cache
Workload:
4,096 token context; Unknown; Unknown; concurrency 1; batch 1; cache unknown; repetitions Unknown.
Tokenizer:
Pinned public Llama Guard 4 tokenizer plus Meta classifier template from revision API · Public Unsloth snapshot and Meta native classifier template, independently pinned in artifacts and download steps
Sampling / reasoning:
Greedy do_sample=False; author max_new_tokens 32 and repetition_penalty 1.0. Native generation config supplies EOS IDs and pad token. Dynamic rather than native static cache avoids allocating the architectural maximum; actual memory remains unknown. Safety classifier generates label text, not chat answers or free reasoning. Fixed native policy: 14 text categories S1–S14. One user input only; system/assistant history, response filtering, category customization and tool execution are not implemented.
Runtime prerequisites:
Ubuntu 24.04 x86_64; See prerequisites above.

Official artifact · License

Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.

  • All 24,002,322,024 original weight bytes load. FP32 doubles BF16 weight storage in memory before cache, compute/vision buffers and OS; exact startup and peak remain unknown.
  • The classifier is dense after pruning; no Scout routed-expert or active-parameter memory discount applies. 64 GiB RAM, 80 GiB disk and eight threads are planning allocations, not confirmed fit/minima.

One-time setup and hardware

hardware
Not applicable — AWS hardware acquisition is included in compute rental; no purchased GPU required. Any separate hardware cost is not applicable.
AWS hardware acquisition is included in compute rental; no purchased GPU required. Any separate hardware cost is not applicable. Tax: unknown.
setup
Unknown — Initial provisioning/build time and labor cost are unknown.
Initial provisioning/build time and labor cost are unknown. Tax: unknown.

Recurring costs

compute
$0.53 / hour
AWS published us-east-1 Linux On-Demand quote USD 0.5292 per billed instance-hour, no paid preinstalled software. Eight billed hours cost USD 4.2336; 24 hours USD 12.7008 compute. Idle running hours bill. No discount, Spot or reservation assumed. Storage, egress, tax and administration additional; capacity unknown. Region: us-east-1. SKU: r7i.2xlarge Linux On-Demand. Tax: excluded. Price dated Oct 15, 2026. Price source
storage
$0.08 / GB month
Captured us-east-1 gp3 quote USD 0.08 per GB-month, with GB defined as 1024^3 bytes. Selected 80 GiB root volume costs USD 6.40 per full month, prorated by provisioned duration, at baseline 3000 IOPS and 125 MB/s. No provisioned extras assumed; retained snapshots/resources separate. Storage persists after stop; tax excluded. Region: us-east-1. SKU: EBS gp3 baseline 3000 IOPS / 125 MB/s. Tax: excluded. Price dated Oct 16, 2026. Price source
egress
Unknown — Data transfer price, allowances and traffic volume are unknown.
Data transfer price, allowances and traffic volume are unknown. Tax: unknown.
administration
Unknown — Maintenance labor rate and hours are unknown.
Maintenance labor rate and hours are unknown. Tax: unknown.

Install the runtime

  1. 1. Create the exact CPU package environment

    Use the official hash-pinned Torch/TorchVision CPU wheels and native Transformers release. TorchVision supports the native fast image processor, including when a text-only model loads its processor. Transitive/system packages resolve at installation; save versions and stop on conflicts. No installation was executed by the author.

    Command
    sudo apt-get update
    sudo apt-get install -y python3.12 python3.12-venv curl ca-certificates openssl
    mkdir -p "$HOME/llama-guard4-hosting/model"
    cd "$HOME/llama-guard4-hosting"
    python3.12 -m venv .venv
    .venv/bin/python -m pip install 'https://download.pytorch.org/whl/cpu/torch-2.6.0%2Bcpu-cp312-cp312-linux_x86_64.whl#sha256=59e78aa0c690f70734e42670036d6b541930b8eabbaa18d94e090abf14cc4d91' 'https://download-r2.pytorch.org/whl/cpu/torchvision-0.21.0%2Bcpu-cp312-cp312-linux_x86_64.whl#sha256=d6874431e678ba107b60a83f255c33f3755f06bad587b1b919aa514ec325dcd8'
    .venv/bin/python -m pip install 'transformers==4.57.6' pillow
    .venv/bin/python -m pip check
    .venv/bin/python -m pip freeze > resolved-environment.txt

    Expected result: pip hash checks and pip check pass; actual environment is recorded. No CUDA driver or remote model code is used.

Download the model

  1. 1. Download and verify all original derivative weight shards

    Fetch the complete public Unsloth artifact, not gated Meta weight URLs. Verify exact sizes and SHA256s. Existing valid files are reused; partial files cannot replace final files before verification.

    Command
    cd "$HOME/llama-guard4-hosting"
    .venv/bin/python - <<'PYDOWNLOAD'
    import pathlib,json,urllib.request,hashlib
    manifest=json.loads("{\"model-00001-of-00005.safetensors\":{\"bytes\":4997861792,\"sha256\":\"1b3e93a5c09f732537068482a5f00c29a675092f0ae456ebd60043af59c21299\"},\"model-00002-of-00005.safetensors\":{\"bytes\":4981018296,\"sha256\":\"08150644f6be3ae2474a8a9f3290edbc62ac876522217c6bf70ce304ed1351e2\"},\"model-00003-of-00005.safetensors\":{\"bytes\":4991503856,\"sha256\":\"1d30c028733fc776ac18a369d565bb395fa4473aa2317cbedeef1cd216c6b327\"},\"model-00004-of-00005.safetensors\":{\"bytes\":4991503856,\"sha256\":\"ecd9fed60f059359941913c3ade611e8c67a63ba453efbc071de8af007c586e7\"},\"model-00005-of-00005.safetensors\":{\"bytes\":4040434224,\"sha256\":\"57aa2d6a20feb15010f74599e4a4f9f4985cb1b87a975dc6ffc1d34780de7599\"}}")
    for name,meta in manifest.items():
     path=pathlib.Path('model')/name
     def valid(p):
      if not p.exists() or p.stat().st_size!=meta['bytes']:return False
      h=hashlib.sha256()
      with p.open('rb') as f:
       for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
      return h.hexdigest()==meta['sha256']
     if not valid(path):
      tmp=path.with_name(path.name+'.partial')
      with urllib.request.urlopen('https://huggingface.co/unsloth/Llama-Guard-4-12B/resolve/07ebbb7bdc44fb45bf710a9a69a82c088085f0c8/'+name) as response,tmp.open('wb') as out:
       while True:
        b=response.read(8*1024*1024)
        if not b:break
        out.write(b)
      assert valid(tmp),name+' hash/size mismatch';tmp.replace(path)
     assert valid(path);print(name,'OK')
    PYDOWNLOAD

    Expected result: All five original weight shards report OK; total weight bytes 24,002,322,024. No model loads.

  2. 2. Download every required config, tokenizer, processor and license file

    Every required auxiliary is pinned. The independently published Unsloth template adds a BOS prefix; do not use it. The next step extracts the original Meta template from the public metadata API instead.

    Command
    cd "$HOME/llama-guard4-hosting"
    .venv/bin/python - <<'PYDOWNLOAD'
    import pathlib,json,urllib.request,hashlib
    manifest=json.loads("{\"LICENSE\":{\"bytes\":7554,\"sha256\":\"73755cee886613ae3135140882289e0a4955d5f0e90f8b1c1ffc962aa9082917\"},\"USE_POLICY.md\":{\"bytes\":5796,\"sha256\":\"5ae40fe842b87b5773c47cfd25992a496cc09b17cbb246968762f06352d89270\"},\"config.json\":{\"bytes\":2789,\"sha256\":\"344ab345ed1268f17e1d6f7d8eb3947b56ac90ca28834c18c171b64a026563cc\"},\"generation_config.json\":{\"bytes\":222,\"sha256\":\"edf659fdf486cfa5eb4cf127cac2dbac0f24f69439051f5111c66d72e47c31df\"},\"model.safetensors.index.json\":{\"bytes\":95229,\"sha256\":\"cdcb8ad59ccafa69c79df8cd9f109453293c613241dd03e216df01f19538dacd\"},\"preprocessor_config.json\":{\"bytes\":636,\"sha256\":\"11a1b41f43161e324bf8302299bce8d59aba671d1505137d9d01179ae9aeacde\"},\"processor_config.json\":{\"bytes\":128,\"sha256\":\"bfc23f929e2a90ba534426072b2e0288909820f34ae79d8ff3934edda29e1f3a\"},\"special_tokens_map.json\":{\"bytes\":451,\"sha256\":\"3484f80da421ad864f1646dd563b8b772ebc9666c34a19d199d6d481c96d1eda\"},\"tokenizer.json\":{\"bytes\":27948580,\"sha256\":\"22e009b4fcb58eddbabf347e71b9881ea1e6eb72d44e5ea9477c7587df68fd8d\"},\"tokenizer_config.json\":{\"bytes\":235854,\"sha256\":\"13bb887373efca2fea1225d3051500e7b0b215824eeaa5d0ba7c2ce85985ff7f\"}}")
    for name,meta in manifest.items():
     path=pathlib.Path('model')/name
     def valid(p):
      if not p.exists() or p.stat().st_size!=meta['bytes']:return False
      h=hashlib.sha256()
      with p.open('rb') as f:
       for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
      return h.hexdigest()==meta['sha256']
     if not valid(path):
      tmp=path.with_name(path.name+'.partial')
      with urllib.request.urlopen('https://huggingface.co/unsloth/Llama-Guard-4-12B/resolve/07ebbb7bdc44fb45bf710a9a69a82c088085f0c8/'+name) as response,tmp.open('wb') as out:
       while True:
        b=response.read(8*1024*1024)
        if not b:break
        out.write(b)
      assert valid(tmp),name+' hash/size mismatch';tmp.replace(path)
     assert valid(path);print(name,'OK')
    PYDOWNLOAD

    Expected result: All ten native-format derivative auxiliaries report OK. No generic Guard 3/Scout template is substituted.

  3. 3. Extract and verify the native Meta classifier template

    The raw native template is gated, but this revision-specific public API exposes its exact string. Verify the full minimal API response bytes, assert the native revision, encode the template string unchanged and verify its derived digest. The API request expands only immutable sha/config fields, avoiding live download counters.

    Command
    cd "$HOME/llama-guard4-hosting"
    curl --fail --location --output native-template-api.json 'https://huggingface.co/api/models/meta-llama/Llama-Guard-4-12B/revision/87acb4b94e930c3d679e6e7ee9d57e2feab9ea71?expand%5B%5D=sha&expand%5B%5D=config'
    sha256sum --check <<'SHA256'
    08b0234e5e3fdd5efb6abfd32d52840eba4b439bba0b11f203df5eea95d08c80  native-template-api.json
    SHA256
    .venv/bin/python - <<'PYTEMPLATE'
    import pathlib,json,hashlib
    meta=json.loads(pathlib.Path('native-template-api.json').read_text())
    assert meta['sha']=='87acb4b94e930c3d679e6e7ee9d57e2feab9ea71'
    raw=meta['config']['chat_template_jinja'].encode('utf-8')
    assert hashlib.sha256(raw).hexdigest()=='40782d45db7ce0d96b0b2595c698e47603e2d459b0390f5025d974c861c53e3b'
    pathlib.Path('native-chat.jinja').write_bytes(raw)
    assert pathlib.Path('native-chat.jinja').read_bytes()==meta['config']['chat_template_jinja'].encode('utf-8')
    print('Native classifier template extracted verbatim and verified')
    PYTEMPLATE

    Expected result: API file reports OK and native template derivation passes. Exactly one template BOS is used with add_special_tokens=False; no Unsloth extra BOS is added.

Configure

  1. 1. Preserve a private service credential

    Generate a local service key only when absent. Keep it private; this is not a provider credential. An empty existing key must be restored, not silently rotated.

    Command
    cd "$HOME/llama-guard4-hosting"
    umask 077
    if [ ! -e .api-key ]; then openssl rand -hex 32 > .api-key; fi
    test -s .api-key || { echo 'Restore empty key before proceeding'; exit 1; }
    chmod 600 .api-key

    Expected result: A nonempty mode600 key exists; no secret is printed.

  2. 2. Write the private classifier wrapper

    This reader-authored serial HTTPServer implements the documented fixed classifier workflow, not an official Meta server. Native eager attention and dense-layer assertions avoid treating the pruned model as Scout MoE. It checks actual full policy/image token count before generating, and validates native labels without converting invalid output to safe.

    Command
    cd "$HOME/llama-guard4-hosting"
    cat > guard_server.py <<'PYSERVER'
    """Reader-authored private educational classifier, not an official Meta server."""
    import base64,hmac,io,json,os,re
    from http.server import BaseHTTPRequestHandler,HTTPServer
    
    def check_budget(count,limit):
        if count>4032 or count+limit>4096: raise ValueError('input_or_budget')
    
    def parse_label(raw,image_mode):
        raw=raw.strip()
        if raw=='safe': return {'label':'safe','categories':[]}
        match=re.fullmatch(r'unsafe\s*\n\s*(S[0-9]+(?:\s*,\s*S[0-9]+)*)',raw)
        if not match: raise ValueError('invalid_classifier_output')
        keys=[x.strip() for x in match[1].split(',')]
        if len(set(keys))!=len(keys) or any(k not in {'S'+str(i) for i in range(1,14 if image_mode else 15)} for k in keys): raise ValueError('invalid_classifier_output')
        return {'label':'unsafe','categories':keys}
    
    def handler_factory(generate,key,image_mode):
        class Handler(BaseHTTPRequestHandler):
            protocol_version='HTTP/1.0'
            def setup(self):
                super().setup();self.connection.settimeout(10)
            def log_message(self,*args): pass
            def reply(self,status,data):
                body=json.dumps(data,ensure_ascii=False).encode();self.send_response(status)
                self.send_header('Content-Type','application/json; charset=utf-8');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
            def auth(self): return hmac.compare_digest(self.headers.get('Authorization','').encode(),('Bearer '+key).encode())
            def do_GET(self):
                if not self.auth(): return self.reply(401,{'error':'unauthorized'})
                self.reply(200,{'status':'ready'}) if self.path=='/health' else self.reply(404,{'error':'not_found'})
            def do_POST(self):
                if not self.auth(): return self.reply(401,{'error':'unauthorized'})
                if self.path!='/v1/guard': return self.reply(404,{'error':'not_found'})
                if self.headers.get('Transfer-Encoding') is not None: return self.reply(400,{'error':'unsupported_transfer_encoding'})
                if self.headers.get_content_type()!='application/json': return self.reply(415,{'error':'json_required'})
                lengths=self.headers.get_all('Content-Length',[])
                if len(lengths)!=1 or not lengths[0] or not all('0'<=c<='9' for c in lengths[0]): return self.reply(411,{'error':'content_length_required'})
                if len(lengths[0])>6: return self.reply(413,{'error':'body_limit'})
                n=int(lengths[0])
                if not 1<=n<=360000: return self.reply(413,{'error':'body_limit'})
                try:
                    raw=self.rfile.read(n)
                    if len(raw)!=n: return self.reply(400,{'error':'incomplete_body'})
                    data=json.loads(raw)
                except (ValueError,UnicodeError,TimeoutError): return self.reply(400,{'error':'invalid_json'})
                fields={'text','max_new_tokens'}|({'image_base64'} if image_mode else set())
                if type(data)!=dict or set(data)!=fields: return self.reply(400,{'error':'invalid_fields'})
                if type(data['text'])!=str or not data['text'].strip() or type(data['max_new_tokens'])!=int or not 1<=data['max_new_tokens']<=64: return self.reply(400,{'error':'invalid_fields'})
                try: text_size=len(data['text'].encode('utf-8'))
                except UnicodeError: return self.reply(400,{'error':'invalid_text'})
                if text_size>2048: return self.reply(400,{'error':'invalid_text'})
                image=None
                if image_mode:
                    if type(data['image_base64'])!=str or len(data['image_base64'])>349528: return self.reply(400,{'error':'invalid_image'})
                    try: image=base64.b64decode(data['image_base64'],validate=True)
                    except ValueError: return self.reply(400,{'error':'invalid_image'})
                    if not 1<=len(image)<=262144: return self.reply(400,{'error':'invalid_image'})
                try: result=generate(data['text'],data['max_new_tokens'],image)
                except ValueError: return self.reply(422,{'error':'input_budget_or_classifier_format'})
                except Exception: return self.reply(500,{'error':'classification_failed'})
                self.reply(200,result)
        return Handler
    
    def main():
        import warnings,torch
        from PIL import Image
        from transformers import AutoProcessor,Llama4ForConditionalGeneration
        image_mode=os.environ.get('GUARD_IMAGE_MODE')=='1'
        key=open('.api-key').read().strip()
        if len(key)!=64 or any(c not in '0123456789abcdef' for c in key): raise SystemExit('Invalid private key')
        torch.set_num_threads(8)
        processor=AutoProcessor.from_pretrained('./model',local_files_only=True,trust_remote_code=False)
        processor.chat_template=open('native-chat.jinja').read()
        model=Llama4ForConditionalGeneration.from_pretrained('./model',local_files_only=True,trust_remote_code=False,dtype=torch.float32,attn_implementation='eager').to('cpu').eval()
        cfg=model.config.text_config
        assert cfg.moe_layers==[] and cfg.num_local_experts==0 and cfg.num_hidden_layers==48 and cfg.hidden_size==5120
        assert all(not layer.is_moe_layer for layer in model.language_model.model.layers)
        assert next(model.parameters()).dtype==torch.float32
        Image.MAX_IMAGE_PIXELS=4194304
        warnings.simplefilter('error',Image.DecompressionBombWarning)
        def generate(text,limit,image):
            content=[];images=None
            if image is not None:
                try:
                    with Image.open(io.BytesIO(image)) as source:
                        if source.format not in ('PNG','JPEG') or not 1<=source.width<=2048 or not 1<=source.height<=2048: raise ValueError('image_bounds')
                        images=[source.convert('RGB')]
                except (OSError,Image.DecompressionBombError,Image.DecompressionBombWarning) as error: raise ValueError('image_decode') from error
                content.append({'type':'image'})
            content.append({'type':'text','text':text})
            prompt=processor.apply_chat_template([{'role':'user','content':content}],tokenize=False,add_generation_prompt=True,excluded_category_keys=[])
            inputs=processor(text=[prompt],images=images,max_patches=1,add_special_tokens=False,return_tensors='pt')
            count=inputs['input_ids'].shape[-1];check_budget(count,limit)
            assert inputs['input_ids'][0,0].item()==processor.tokenizer.bos_token_id
            with torch.inference_mode():
                out=model.generate(**inputs,max_new_tokens=limit,do_sample=False,repetition_penalty=1.0,cache_implementation='dynamic',pad_token_id=processor.tokenizer.pad_token_id)
            new=out[0,count:];raw=processor.tokenizer.decode(new,skip_special_tokens=True).strip()
            parsed=parse_label(raw,image_mode)
            if len(new)==limit: raise ValueError('classifier_output_cap')
            return {**parsed,'raw_label':raw,'input_tokens':count,'output_tokens':len(new),'policy_categories':13 if image_mode else 14}
        HTTPServer(('127.0.0.1',8996),handler_factory(generate,key,image_mode)).serve_forever()
    if __name__=='__main__': main()
    PYSERVER
    .venv/bin/python -m py_compile guard_server.py

    Expected result: Syntax check succeeds. Wrapper bytes match the source shown; py_compile does not import the model.

Start the model

  1. 1. Start the text-only input classifier

    Run in a foreground terminal. Loads all local weights and integrated vision components in CPU FP32 with eager attention. The exact native template replaces processor defaults. One sequence is served at a time; no generation deadline or public-server resilience is claimed.

    Command
    cd "$HOME/llama-guard4-hosting"
    GUARD_IMAGE_MODE=0 .venv/bin/python guard_server.py

    Expected result: After successful startup, authenticated health reports ready. Stop on model/tokenizer/dense-layer/import/RAM errors. Actual startup has not been executed here.

Connect to your endpoint

http://127.0.0.1:8996/v1/guard

Server loopback only. For a remote client use existing SSH: ssh -N -L 8996:127.0.0.1:8996 USER@VM_IP. Keep public8996 closed. The documented verification reads the private key on the VM.

Access: loopback. Reader-generated Bearer key protects health and classifier routes. Request fields are text and max_new_tokens; image_base64 is rejected in text mode. Response fields are label, categories, raw_label, input_tokens, output_tokens and policy_categories. No chat roles, arbitrary URL fetching or provider API is exposed.

Verify the setup

  1. 1. Verify readiness, native label response and authentication

    Run in a second terminal on the same desktop or VM SSH shell. The benign greeting is expected to classify safe under the fixed text policy. This is a reader pass criterion, not an observed classifier result, calibrated score or safety guarantee. The endpoint returns labels rather than answering the greeting. Accept a complete parsed label only; invalid/empty output, cap exhaustion, context error or unexpected category fails this check.

    Command
    cd "$HOME/llama-guard4-hosting"
    printf '%s\n' '{"text":"Hello! I hope you have a nice day.","max_new_tokens":32}' > guard-request.json
    GUARD_SERVICE_KEY="$(cat .api-key)"
    curl --fail http://127.0.0.1:8996/health -H "Authorization: Bearer $GUARD_SERVICE_KEY"
    curl --fail http://127.0.0.1:8996/v1/guard -H "Authorization: Bearer $GUARD_SERVICE_KEY" -H 'Content-Type: application/json' --data-binary @guard-request.json --output guard-response.json
    cat guard-response.json
    .venv/bin/python - <<'PYRESULT'
    import json
    r=json.load(open('guard-response.json'))
    assert r['label']=='safe' and r['categories']==[] and r['policy_categories']==14
    assert 1<=r['output_tokens']<32 and r['input_tokens']+r['output_tokens']<=4096
    print('Expected native safe label and token-budget checks passed; not a general safety guarantee')
    PYRESULT
    curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8996/health
    unset GUARD_SERVICE_KEY

    Expected result: Authorized health returns ready; classification returns safe, empty categories and native policy count 14. Missing key returns401. Exact raw label text/token counts are unknown; no inference result is claimed.

Performance evidence

No compatible measurement available. Documented support and estimated memory do not establish response speed.

Limits and troubleshooting

  • Documented only: no weights, packages, model imports, installation, build or inference executed. Full fit, latency, throughput and classifier accuracy remain unknown.
  • Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.
  • The public derivative has the same five shard sizes as the gated native listing, but native LFS digests are redacted. That does not establish byte equivalence or an exact upstream conversion revision. All runnable derivative bytes are pinned independently.
  • The exact native policy template is extracted from a revision-specific public API; its full API bytes and derived UTF-8 string are verified. Mirror template adds an extra BOS prefix and is deliberately not used. add_special_tokens=False prevents automatic extra BOS.
  • Native Guard4 is dense after pruning:48 layers, hidden5120,40Q/8KV heads, no routed experts, empty moe_layers. Transformers uses a dense MLP path; eager attention is explicitly selected for text and vision. No Guard3 or generic Scout runtime behavior is assumed.
  • Fixed native template has13 image categories and14 text categories; S14 Code Interpreter Abuse is text-only. Parser rejects unexpected/duplicate category IDs, invalid/empty labels and cap exhaustion. A valid format does not establish a correct prediction.
  • Only one user input is classified. Response classification, multi-turn parity/assistant history, category customization, multilingual performance, multi-image inputs, full context and other runtimes/devices remain separate unqualified useful scopes.
  • The reader-authored endpoint is serial and private: authenticated health/classification,360000-byte body limit, strict fields/types,10-second socket read timeout, at most2048 UTF-8 text bytes, actual full input<=4032 and input+requested output<=4096. Requests allow1–64 new tokens; smoke uses32. No generation timeout, TLS/public hardening or calibrated probability is provided.
  • Image mode accepts one validated-base64 PNG/JPEG up to262144 decoded bytes and2048 by2048 pixels. Native max_patches1 resizes to one336-square tile; actual rendered policy/image/text tokens are checked before generation. Text mode accepts no image field.
  • Full FP32 weights, vision components, cache, buffers and OS share system RAM.64 GiB RAM,80 GiB disk and eight threads are allocations, not measured minima or confirmed fit.
  • Guard4 labels can have false positives and false negatives, and policy alignment may differ from your intended use. A safe label is not a universal assurance; the narrow benign fixture is not a quality benchmark.
  • System and transitive packages resolve at installation. Exact Torch/TorchVision wheel hashes and Transformers version are supplied, but target Python3.12 model/processor startup compatibility remains unexecuted.
  • Two modality pairs do not establish exhaustive model coverage. Original cloud quote dates and unknown egress/tax/admin are retained; local purchase/power remain unknown.
401 or connection refused
Check foreground startup and matching private key. For cloud check existing SSH tunnel and keep public8996 closed.
400,411,413,415 or422 response
Use exact mode-specific fields, JSON media type, one ASCII Content-Length and bounded text/image bytes. Check actual policy+image input tokens and requested generation cap. Invalid native label/category or exhausted cap is a failed classification, never an automatic safe result.
Unexpected label or category
Inspect raw_label and the native fixed policy. S14 exists only for text. Record false positive/negative behavior; do not reinterpret model labels as guaranteed safe or substitute general chat output.
Model/tokenizer/dense assertion or memory error
Stop. Verify all independent derivative hashes, native API/template derivation and exact CPU packages. Do not substitute Guard3, enable routed Scout experts, remove required assertions or silently change resource/precision.

Stop the model

  1. 1. Stop classifier and tunnel

    Press Ctrl+C in the foreground Python terminal. Unset client keys; close any SSH tunnel with Ctrl+C. Stopping Python alone does not stop EC2 billing.

    Command
    unset GUARD_SERVICE_KEY

    Expected result: Foreground service stops and loopback8996 no longer responds.

Uninstall

  1. 1. Remove dedicated files

    After confirming the path and preserving wanted diagnostics, remove only this walkthrough directory. Shared apt packages remain.

    Command
    rm -r -- "$HOME/llama-guard4-hosting"

    Expected result: Dedicated weights, venv, wrapper, template/API metadata, requests/responses and private key are removed.

Shut down cloud resources

  1. 1. End cloud billing resources

    In EC2 us-east-1, stop for later reuse or terminate this exact VM. Review Delete on termination for its root volume. Delete unwanted detached EBS volumes, snapshots and reserved/Elastic/public IP resources. Stopped VM storage and retained resources may still bill. Check Bills/Cost Explorer later for final usage.

    Expected result: Exact instance is stopped/terminated as intended; no unwanted attached/retained billed resources remain. Instance compute stops only after its lifecycle transition, not when the Python classifier stops.

Sources and verification

Sources checked Oct 16, 2026. Verification source

Compare this configuration
Local hardwareDocumented setupSources checked Oct 16, 2026

Run Llama Guard 4 image-and-text input classification on a 64 GiB Intel desktop

Classify one image plus text using the exact public Unsloth Llama Guard 4 snapshot, Meta classification template and native dense Transformers CPU FP32 path. A reader-authored private endpoint returns safe/unsafe and 13-category labels. One request, 4,096 total tokens and a 32-token greedy check. Fit, speed and classifier accuracy remain unmeasured.

Hardware
Intel Core i5-12400 desktop, 8 inference threads, 64 GiB RAM
Runtime
Native dense Llama Guard 4 CPU classifier with reader-authored private endpoint Python 3.12; Torch 2.6.0+cpu; TorchVision 0.21.0+cpu; Transformers 4.57.6; FP32 eager attention · CPU
Model format
safetensors · Full native BF16 artifact explicitly loaded as CPU FP32 · No quantization; original BF16 snapshot converted to FP32 on CPU
Workload
4,096 token context · 1 concurrent

Based on source documentation; this setup has not been executed by OpenTools. Memory: unknown. No compatible measurement available.

Read the complete setup guide

Before you start

  • Use an owned Intel Core i5-12400 Ubuntu 24.04 x86_64 desktop with 64 GiB RAM, 80 GiB free disk and eight allocated inference threads.
  • Use the exact independently public Unsloth snapshot, native Meta classifier template and pinned CPU Python packages. Meta raw checkpoint files remain manually gated; no credential, native download approval or exact byte equivalence is inferred.
  • Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.
  • The fixed single-user image-and-text input classifier is not a general assistant or a guarantee that content is safe. Model labels can be wrong; evaluate your intended policy/workload before relying on results.

Exact model and requirements

Artifact:
Unsloth (public snapshot); Meta (native classifier) / Public Unsloth Llama-Guard-4-12B full five-shard BF16 snapshot · checkpoint unsloth/Llama-Guard-4-12B
Publisher revision:
07ebbb7bdc44fb45bf710a9a69a82c088085f0c8
Artifact digest:
No publisher single-file digest for this multi-file snapshot. Mandatory recipe verifies all five weight SHA256s and every required auxiliary; no index hash is called a whole-weight digest.
Download size:
22.35 GiB
Memory requirement (unknown):
Unknown — No measured full CPU peak for this 12B dense model loaded FP32, native vision encoder and 4K bounded classifier workload.
System RAM / disk:
Unknown / Unknown
Placement:
single device. One CPU host, no tensor or pipeline sharding. Entire dense text model, integrated vision encoder and projector stay on CPU. No GPU, disk offload, device_map or active-expert weight reduction.
KV cache:
FP32 native attention K/V with author-selected dynamic cache
Workload:
4,096 token context; Unknown; Unknown; concurrency 1; batch 1; cache unknown; repetitions Unknown.
Tokenizer:
Pinned public Llama Guard 4 tokenizer plus Meta classifier template from revision API · Public Unsloth snapshot and Meta native classifier template, independently pinned in artifacts and download steps
Sampling / reasoning:
Greedy do_sample=False; author max_new_tokens 32 and repetition_penalty 1.0. Native generation config supplies EOS IDs and pad token. Dynamic rather than native static cache avoids allocating the architectural maximum; actual memory remains unknown. Safety classifier generates label text, not chat answers or free reasoning. Fixed native policy: 13 image categories S1–S13. One user input only; system/assistant history, response filtering, category customization and tool execution are not implemented.
Runtime prerequisites:
Ubuntu 24.04 x86_64; See prerequisites above.

Official artifact · License

Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.

  • All 24,002,322,024 original weight bytes load. FP32 doubles BF16 weight storage in memory before cache, compute/vision buffers and OS; exact startup and peak remain unknown.
  • The classifier is dense after pruning; no Scout routed-expert or active-parameter memory discount applies. 64 GiB RAM, 80 GiB disk and eight threads are planning allocations, not confirmed fit/minima.

One-time setup and hardware

hardware
Unknown — Existing desktop purchase price and incremental hardware cost depend on the reader; unknown.
Existing desktop purchase price and incremental hardware cost depend on the reader; unknown. Tax: unknown.
setup
Unknown — Initial provisioning/build time and labor cost are unknown.
Initial provisioning/build time and labor cost are unknown. Tax: unknown.

Recurring costs

electricity
Unknown — Actual wall power, electricity rate and powered hours are unknown; no TDP-to-wall-power conversion.
Actual wall power, electricity rate and powered hours are unknown; no TDP-to-wall-power conversion. Tax: unknown.
storage
Unknown — Incremental cost of local disk capacity is unknown. The 80 GiB free-disk walkthrough allocation is an author choice, not a measured requirement.
Incremental cost of local disk capacity is unknown. The 80 GiB free-disk walkthrough allocation is an author choice, not a measured requirement. Tax: unknown.
egress
Unknown — Data transfer price, allowances and traffic volume are unknown.
Data transfer price, allowances and traffic volume are unknown. Tax: unknown.
administration
Unknown — Maintenance labor rate and hours are unknown.
Maintenance labor rate and hours are unknown. Tax: unknown.

Install the runtime

  1. 1. Create the exact CPU package environment

    Use the official hash-pinned Torch/TorchVision CPU wheels and native Transformers release. TorchVision supports the native fast image processor, including when a text-only model loads its processor. Transitive/system packages resolve at installation; save versions and stop on conflicts. No installation was executed by the author.

    Command
    sudo apt-get update
    sudo apt-get install -y python3.12 python3.12-venv curl ca-certificates openssl
    mkdir -p "$HOME/llama-guard4-hosting/model"
    cd "$HOME/llama-guard4-hosting"
    python3.12 -m venv .venv
    .venv/bin/python -m pip install 'https://download.pytorch.org/whl/cpu/torch-2.6.0%2Bcpu-cp312-cp312-linux_x86_64.whl#sha256=59e78aa0c690f70734e42670036d6b541930b8eabbaa18d94e090abf14cc4d91' 'https://download-r2.pytorch.org/whl/cpu/torchvision-0.21.0%2Bcpu-cp312-cp312-linux_x86_64.whl#sha256=d6874431e678ba107b60a83f255c33f3755f06bad587b1b919aa514ec325dcd8'
    .venv/bin/python -m pip install 'transformers==4.57.6' pillow
    .venv/bin/python -m pip check
    .venv/bin/python -m pip freeze > resolved-environment.txt

    Expected result: pip hash checks and pip check pass; actual environment is recorded. No CUDA driver or remote model code is used.

Download the model

  1. 1. Download and verify all original derivative weight shards

    Fetch the complete public Unsloth artifact, not gated Meta weight URLs. Verify exact sizes and SHA256s. Existing valid files are reused; partial files cannot replace final files before verification.

    Command
    cd "$HOME/llama-guard4-hosting"
    .venv/bin/python - <<'PYDOWNLOAD'
    import pathlib,json,urllib.request,hashlib
    manifest=json.loads("{\"model-00001-of-00005.safetensors\":{\"bytes\":4997861792,\"sha256\":\"1b3e93a5c09f732537068482a5f00c29a675092f0ae456ebd60043af59c21299\"},\"model-00002-of-00005.safetensors\":{\"bytes\":4981018296,\"sha256\":\"08150644f6be3ae2474a8a9f3290edbc62ac876522217c6bf70ce304ed1351e2\"},\"model-00003-of-00005.safetensors\":{\"bytes\":4991503856,\"sha256\":\"1d30c028733fc776ac18a369d565bb395fa4473aa2317cbedeef1cd216c6b327\"},\"model-00004-of-00005.safetensors\":{\"bytes\":4991503856,\"sha256\":\"ecd9fed60f059359941913c3ade611e8c67a63ba453efbc071de8af007c586e7\"},\"model-00005-of-00005.safetensors\":{\"bytes\":4040434224,\"sha256\":\"57aa2d6a20feb15010f74599e4a4f9f4985cb1b87a975dc6ffc1d34780de7599\"}}")
    for name,meta in manifest.items():
     path=pathlib.Path('model')/name
     def valid(p):
      if not p.exists() or p.stat().st_size!=meta['bytes']:return False
      h=hashlib.sha256()
      with p.open('rb') as f:
       for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
      return h.hexdigest()==meta['sha256']
     if not valid(path):
      tmp=path.with_name(path.name+'.partial')
      with urllib.request.urlopen('https://huggingface.co/unsloth/Llama-Guard-4-12B/resolve/07ebbb7bdc44fb45bf710a9a69a82c088085f0c8/'+name) as response,tmp.open('wb') as out:
       while True:
        b=response.read(8*1024*1024)
        if not b:break
        out.write(b)
      assert valid(tmp),name+' hash/size mismatch';tmp.replace(path)
     assert valid(path);print(name,'OK')
    PYDOWNLOAD

    Expected result: All five original weight shards report OK; total weight bytes 24,002,322,024. No model loads.

  2. 2. Download every required config, tokenizer, processor and license file

    Every required auxiliary is pinned. The independently published Unsloth template adds a BOS prefix; do not use it. The next step extracts the original Meta template from the public metadata API instead.

    Command
    cd "$HOME/llama-guard4-hosting"
    .venv/bin/python - <<'PYDOWNLOAD'
    import pathlib,json,urllib.request,hashlib
    manifest=json.loads("{\"LICENSE\":{\"bytes\":7554,\"sha256\":\"73755cee886613ae3135140882289e0a4955d5f0e90f8b1c1ffc962aa9082917\"},\"USE_POLICY.md\":{\"bytes\":5796,\"sha256\":\"5ae40fe842b87b5773c47cfd25992a496cc09b17cbb246968762f06352d89270\"},\"config.json\":{\"bytes\":2789,\"sha256\":\"344ab345ed1268f17e1d6f7d8eb3947b56ac90ca28834c18c171b64a026563cc\"},\"generation_config.json\":{\"bytes\":222,\"sha256\":\"edf659fdf486cfa5eb4cf127cac2dbac0f24f69439051f5111c66d72e47c31df\"},\"model.safetensors.index.json\":{\"bytes\":95229,\"sha256\":\"cdcb8ad59ccafa69c79df8cd9f109453293c613241dd03e216df01f19538dacd\"},\"preprocessor_config.json\":{\"bytes\":636,\"sha256\":\"11a1b41f43161e324bf8302299bce8d59aba671d1505137d9d01179ae9aeacde\"},\"processor_config.json\":{\"bytes\":128,\"sha256\":\"bfc23f929e2a90ba534426072b2e0288909820f34ae79d8ff3934edda29e1f3a\"},\"special_tokens_map.json\":{\"bytes\":451,\"sha256\":\"3484f80da421ad864f1646dd563b8b772ebc9666c34a19d199d6d481c96d1eda\"},\"tokenizer.json\":{\"bytes\":27948580,\"sha256\":\"22e009b4fcb58eddbabf347e71b9881ea1e6eb72d44e5ea9477c7587df68fd8d\"},\"tokenizer_config.json\":{\"bytes\":235854,\"sha256\":\"13bb887373efca2fea1225d3051500e7b0b215824eeaa5d0ba7c2ce85985ff7f\"}}")
    for name,meta in manifest.items():
     path=pathlib.Path('model')/name
     def valid(p):
      if not p.exists() or p.stat().st_size!=meta['bytes']:return False
      h=hashlib.sha256()
      with p.open('rb') as f:
       for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
      return h.hexdigest()==meta['sha256']
     if not valid(path):
      tmp=path.with_name(path.name+'.partial')
      with urllib.request.urlopen('https://huggingface.co/unsloth/Llama-Guard-4-12B/resolve/07ebbb7bdc44fb45bf710a9a69a82c088085f0c8/'+name) as response,tmp.open('wb') as out:
       while True:
        b=response.read(8*1024*1024)
        if not b:break
        out.write(b)
      assert valid(tmp),name+' hash/size mismatch';tmp.replace(path)
     assert valid(path);print(name,'OK')
    PYDOWNLOAD

    Expected result: All ten native-format derivative auxiliaries report OK. No generic Guard 3/Scout template is substituted.

  3. 3. Extract and verify the native Meta classifier template

    The raw native template is gated, but this revision-specific public API exposes its exact string. Verify the full minimal API response bytes, assert the native revision, encode the template string unchanged and verify its derived digest. The API request expands only immutable sha/config fields, avoiding live download counters.

    Command
    cd "$HOME/llama-guard4-hosting"
    curl --fail --location --output native-template-api.json 'https://huggingface.co/api/models/meta-llama/Llama-Guard-4-12B/revision/87acb4b94e930c3d679e6e7ee9d57e2feab9ea71?expand%5B%5D=sha&expand%5B%5D=config'
    sha256sum --check <<'SHA256'
    08b0234e5e3fdd5efb6abfd32d52840eba4b439bba0b11f203df5eea95d08c80  native-template-api.json
    SHA256
    .venv/bin/python - <<'PYTEMPLATE'
    import pathlib,json,hashlib
    meta=json.loads(pathlib.Path('native-template-api.json').read_text())
    assert meta['sha']=='87acb4b94e930c3d679e6e7ee9d57e2feab9ea71'
    raw=meta['config']['chat_template_jinja'].encode('utf-8')
    assert hashlib.sha256(raw).hexdigest()=='40782d45db7ce0d96b0b2595c698e47603e2d459b0390f5025d974c861c53e3b'
    pathlib.Path('native-chat.jinja').write_bytes(raw)
    assert pathlib.Path('native-chat.jinja').read_bytes()==meta['config']['chat_template_jinja'].encode('utf-8')
    print('Native classifier template extracted verbatim and verified')
    PYTEMPLATE

    Expected result: API file reports OK and native template derivation passes. Exactly one template BOS is used with add_special_tokens=False; no Unsloth extra BOS is added.

Configure

  1. 1. Preserve a private service credential

    Generate a local service key only when absent. Keep it private; this is not a provider credential. An empty existing key must be restored, not silently rotated.

    Command
    cd "$HOME/llama-guard4-hosting"
    umask 077
    if [ ! -e .api-key ]; then openssl rand -hex 32 > .api-key; fi
    test -s .api-key || { echo 'Restore empty key before proceeding'; exit 1; }
    chmod 600 .api-key

    Expected result: A nonempty mode600 key exists; no secret is printed.

  2. 2. Write the private classifier wrapper

    This reader-authored serial HTTPServer implements the documented fixed classifier workflow, not an official Meta server. Native eager attention and dense-layer assertions avoid treating the pruned model as Scout MoE. It checks actual full policy/image token count before generating, and validates native labels without converting invalid output to safe.

    Command
    cd "$HOME/llama-guard4-hosting"
    cat > guard_server.py <<'PYSERVER'
    """Reader-authored private educational classifier, not an official Meta server."""
    import base64,hmac,io,json,os,re
    from http.server import BaseHTTPRequestHandler,HTTPServer
    
    def check_budget(count,limit):
        if count>4032 or count+limit>4096: raise ValueError('input_or_budget')
    
    def parse_label(raw,image_mode):
        raw=raw.strip()
        if raw=='safe': return {'label':'safe','categories':[]}
        match=re.fullmatch(r'unsafe\s*\n\s*(S[0-9]+(?:\s*,\s*S[0-9]+)*)',raw)
        if not match: raise ValueError('invalid_classifier_output')
        keys=[x.strip() for x in match[1].split(',')]
        if len(set(keys))!=len(keys) or any(k not in {'S'+str(i) for i in range(1,14 if image_mode else 15)} for k in keys): raise ValueError('invalid_classifier_output')
        return {'label':'unsafe','categories':keys}
    
    def handler_factory(generate,key,image_mode):
        class Handler(BaseHTTPRequestHandler):
            protocol_version='HTTP/1.0'
            def setup(self):
                super().setup();self.connection.settimeout(10)
            def log_message(self,*args): pass
            def reply(self,status,data):
                body=json.dumps(data,ensure_ascii=False).encode();self.send_response(status)
                self.send_header('Content-Type','application/json; charset=utf-8');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
            def auth(self): return hmac.compare_digest(self.headers.get('Authorization','').encode(),('Bearer '+key).encode())
            def do_GET(self):
                if not self.auth(): return self.reply(401,{'error':'unauthorized'})
                self.reply(200,{'status':'ready'}) if self.path=='/health' else self.reply(404,{'error':'not_found'})
            def do_POST(self):
                if not self.auth(): return self.reply(401,{'error':'unauthorized'})
                if self.path!='/v1/guard': return self.reply(404,{'error':'not_found'})
                if self.headers.get('Transfer-Encoding') is not None: return self.reply(400,{'error':'unsupported_transfer_encoding'})
                if self.headers.get_content_type()!='application/json': return self.reply(415,{'error':'json_required'})
                lengths=self.headers.get_all('Content-Length',[])
                if len(lengths)!=1 or not lengths[0] or not all('0'<=c<='9' for c in lengths[0]): return self.reply(411,{'error':'content_length_required'})
                if len(lengths[0])>6: return self.reply(413,{'error':'body_limit'})
                n=int(lengths[0])
                if not 1<=n<=360000: return self.reply(413,{'error':'body_limit'})
                try:
                    raw=self.rfile.read(n)
                    if len(raw)!=n: return self.reply(400,{'error':'incomplete_body'})
                    data=json.loads(raw)
                except (ValueError,UnicodeError,TimeoutError): return self.reply(400,{'error':'invalid_json'})
                fields={'text','max_new_tokens'}|({'image_base64'} if image_mode else set())
                if type(data)!=dict or set(data)!=fields: return self.reply(400,{'error':'invalid_fields'})
                if type(data['text'])!=str or not data['text'].strip() or type(data['max_new_tokens'])!=int or not 1<=data['max_new_tokens']<=64: return self.reply(400,{'error':'invalid_fields'})
                try: text_size=len(data['text'].encode('utf-8'))
                except UnicodeError: return self.reply(400,{'error':'invalid_text'})
                if text_size>2048: return self.reply(400,{'error':'invalid_text'})
                image=None
                if image_mode:
                    if type(data['image_base64'])!=str or len(data['image_base64'])>349528: return self.reply(400,{'error':'invalid_image'})
                    try: image=base64.b64decode(data['image_base64'],validate=True)
                    except ValueError: return self.reply(400,{'error':'invalid_image'})
                    if not 1<=len(image)<=262144: return self.reply(400,{'error':'invalid_image'})
                try: result=generate(data['text'],data['max_new_tokens'],image)
                except ValueError: return self.reply(422,{'error':'input_budget_or_classifier_format'})
                except Exception: return self.reply(500,{'error':'classification_failed'})
                self.reply(200,result)
        return Handler
    
    def main():
        import warnings,torch
        from PIL import Image
        from transformers import AutoProcessor,Llama4ForConditionalGeneration
        image_mode=os.environ.get('GUARD_IMAGE_MODE')=='1'
        key=open('.api-key').read().strip()
        if len(key)!=64 or any(c not in '0123456789abcdef' for c in key): raise SystemExit('Invalid private key')
        torch.set_num_threads(8)
        processor=AutoProcessor.from_pretrained('./model',local_files_only=True,trust_remote_code=False)
        processor.chat_template=open('native-chat.jinja').read()
        model=Llama4ForConditionalGeneration.from_pretrained('./model',local_files_only=True,trust_remote_code=False,dtype=torch.float32,attn_implementation='eager').to('cpu').eval()
        cfg=model.config.text_config
        assert cfg.moe_layers==[] and cfg.num_local_experts==0 and cfg.num_hidden_layers==48 and cfg.hidden_size==5120
        assert all(not layer.is_moe_layer for layer in model.language_model.model.layers)
        assert next(model.parameters()).dtype==torch.float32
        Image.MAX_IMAGE_PIXELS=4194304
        warnings.simplefilter('error',Image.DecompressionBombWarning)
        def generate(text,limit,image):
            content=[];images=None
            if image is not None:
                try:
                    with Image.open(io.BytesIO(image)) as source:
                        if source.format not in ('PNG','JPEG') or not 1<=source.width<=2048 or not 1<=source.height<=2048: raise ValueError('image_bounds')
                        images=[source.convert('RGB')]
                except (OSError,Image.DecompressionBombError,Image.DecompressionBombWarning) as error: raise ValueError('image_decode') from error
                content.append({'type':'image'})
            content.append({'type':'text','text':text})
            prompt=processor.apply_chat_template([{'role':'user','content':content}],tokenize=False,add_generation_prompt=True,excluded_category_keys=[])
            inputs=processor(text=[prompt],images=images,max_patches=1,add_special_tokens=False,return_tensors='pt')
            count=inputs['input_ids'].shape[-1];check_budget(count,limit)
            assert inputs['input_ids'][0,0].item()==processor.tokenizer.bos_token_id
            with torch.inference_mode():
                out=model.generate(**inputs,max_new_tokens=limit,do_sample=False,repetition_penalty=1.0,cache_implementation='dynamic',pad_token_id=processor.tokenizer.pad_token_id)
            new=out[0,count:];raw=processor.tokenizer.decode(new,skip_special_tokens=True).strip()
            parsed=parse_label(raw,image_mode)
            if len(new)==limit: raise ValueError('classifier_output_cap')
            return {**parsed,'raw_label':raw,'input_tokens':count,'output_tokens':len(new),'policy_categories':13 if image_mode else 14}
        HTTPServer(('127.0.0.1',8996),handler_factory(generate,key,image_mode)).serve_forever()
    if __name__=='__main__': main()
    PYSERVER
    .venv/bin/python -m py_compile guard_server.py

    Expected result: Syntax check succeeds. Wrapper bytes match the source shown; py_compile does not import the model.

Start the model

  1. 1. Start the single-image input classifier

    Run in a foreground terminal. Loads all local weights and integrated vision components in CPU FP32 with eager attention. The exact native template replaces processor defaults. One sequence is served at a time; no generation deadline or public-server resilience is claimed.

    Command
    cd "$HOME/llama-guard4-hosting"
    GUARD_IMAGE_MODE=1 .venv/bin/python guard_server.py

    Expected result: After successful startup, authenticated health reports ready. Stop on model/tokenizer/dense-layer/import/RAM errors. Actual startup has not been executed here.

Connect to your endpoint

http://127.0.0.1:8996/v1/guard

Same desktop loopback only, trusted private host.

Access: loopback. Reader-generated Bearer key protects health and classifier routes. Request fields are text and max_new_tokens; image_base64 is additionally required in this image mode. Response fields are label, categories, raw_label, input_tokens, output_tokens and policy_categories. No chat roles, arbitrary URL fetching or provider API is exposed.

Verify the setup

  1. 1. Verify readiness, native label response and authentication

    Run in a second terminal on the same desktop or VM SSH shell. The manually inspected publisher diagram contains Attention/FFN boxes, arrows and a blue dense-feedforward box. Under the fixed image policy the expected smoke label is safe; this is a criterion, not an observed prediction or accuracy claim. No image-description answer should be generated. One PNG/JPEG up to262144 bytes and2048 by2048 pixels is allowed. Native max_patches=1 yields one336-square tile without extra global tile, nominally144 patch placeholders plus markers; actual full input is counted and capped. Accept a complete parsed label only; invalid/empty output, cap exhaustion, context error or unexpected category fails this check.

    Command
    cd "$HOME/llama-guard4-hosting"
    curl --fail --location --output fixture.png 'https://raw.githubusercontent.com/meta-llama/PurpleLlama/d934ea285d124d81c10f7e15a06a1e1f74eff2c3/Llama-Guard4/12B/llama_guard_4_12b_after_pruning.png'
    sha256sum --check <<'SHA256'
    2d5033ef706bf52d4b7ff8a2f76bd211bbdb55ddc791679a9b6968150ebb33ed  fixture.png
    SHA256
    .venv/bin/python - <<'PYREQUEST'
    import pathlib,json,base64,hashlib
    raw=pathlib.Path('fixture.png').read_bytes()
    assert len(raw)==41348 and hashlib.sha256(raw).hexdigest()=='2d5033ef706bf52d4b7ff8a2f76bd211bbdb55ddc791679a9b6968150ebb33ed'
    data={'text':'Please describe the diagram.','max_new_tokens':32,'image_base64':base64.b64encode(raw).decode()}
    pathlib.Path('guard-request.json').write_text(json.dumps(data))
    PYREQUEST
    GUARD_SERVICE_KEY="$(cat .api-key)"
    curl --fail http://127.0.0.1:8996/health -H "Authorization: Bearer $GUARD_SERVICE_KEY"
    curl --fail http://127.0.0.1:8996/v1/guard -H "Authorization: Bearer $GUARD_SERVICE_KEY" -H 'Content-Type: application/json' --data-binary @guard-request.json --output guard-response.json
    cat guard-response.json
    .venv/bin/python - <<'PYRESULT'
    import json
    r=json.load(open('guard-response.json'))
    assert r['label']=='safe' and r['categories']==[] and r['policy_categories']==13
    assert 1<=r['output_tokens']<32 and r['input_tokens']+r['output_tokens']<=4096
    print('Expected native safe label and token-budget checks passed; not a general safety guarantee')
    PYRESULT
    curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8996/health
    unset GUARD_SERVICE_KEY

    Expected result: Authorized health returns ready; classification returns safe, empty categories and native policy count 13. Missing key returns401. Exact raw label text/token counts are unknown; no inference result is claimed.

Performance evidence

No compatible measurement available. Documented support and estimated memory do not establish response speed.

Limits and troubleshooting

  • Documented only: no weights, packages, model imports, installation, build or inference executed. Full fit, latency, throughput and classifier accuracy remain unknown.
  • Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.
  • The public derivative has the same five shard sizes as the gated native listing, but native LFS digests are redacted. That does not establish byte equivalence or an exact upstream conversion revision. All runnable derivative bytes are pinned independently.
  • The exact native policy template is extracted from a revision-specific public API; its full API bytes and derived UTF-8 string are verified. Mirror template adds an extra BOS prefix and is deliberately not used. add_special_tokens=False prevents automatic extra BOS.
  • Native Guard4 is dense after pruning:48 layers, hidden5120,40Q/8KV heads, no routed experts, empty moe_layers. Transformers uses a dense MLP path; eager attention is explicitly selected for text and vision. No Guard3 or generic Scout runtime behavior is assumed.
  • Fixed native template has13 image categories and14 text categories; S14 Code Interpreter Abuse is text-only. Parser rejects unexpected/duplicate category IDs, invalid/empty labels and cap exhaustion. A valid format does not establish a correct prediction.
  • Only one user input is classified. Response classification, multi-turn parity/assistant history, category customization, multilingual performance, multi-image inputs, full context and other runtimes/devices remain separate unqualified useful scopes.
  • The reader-authored endpoint is serial and private: authenticated health/classification,360000-byte body limit, strict fields/types,10-second socket read timeout, at most2048 UTF-8 text bytes, actual full input<=4032 and input+requested output<=4096. Requests allow1–64 new tokens; smoke uses32. No generation timeout, TLS/public hardening or calibrated probability is provided.
  • Image mode accepts one validated-base64 PNG/JPEG up to262144 decoded bytes and2048 by2048 pixels. Native max_patches1 resizes to one336-square tile; actual rendered policy/image/text tokens are checked before generation. Text mode accepts no image field.
  • Full FP32 weights, vision components, cache, buffers and OS share system RAM.64 GiB RAM,80 GiB disk and eight threads are allocations, not measured minima or confirmed fit.
  • Guard4 labels can have false positives and false negatives, and policy alignment may differ from your intended use. A safe label is not a universal assurance; the narrow benign fixture is not a quality benchmark.
  • System and transitive packages resolve at installation. Exact Torch/TorchVision wheel hashes and Transformers version are supplied, but target Python3.12 model/processor startup compatibility remains unexecuted.
  • Publisher diagram is used only in the image guide from its exact official source URL; retain Meta attribution and applicable Llama4 license terms. No broader image-rights clearance is claimed.
  • Two modality pairs do not establish exhaustive model coverage. Original cloud quote dates and unknown egress/tax/admin are retained; local purchase/power remain unknown.
401 or connection refused
Check foreground startup and matching private key. For cloud check existing SSH tunnel and keep public8996 closed.
400,411,413,415 or422 response
Use exact mode-specific fields, JSON media type, one ASCII Content-Length and bounded text/image bytes. Check actual policy+image input tokens and requested generation cap. Invalid native label/category or exhausted cap is a failed classification, never an automatic safe result.
Unexpected label or category
Inspect raw_label and the native fixed policy. S14 exists only for text. Record false positive/negative behavior; do not reinterpret model labels as guaranteed safe or substitute general chat output.
Model/tokenizer/dense assertion or memory error
Stop. Verify all independent derivative hashes, native API/template derivation and exact CPU packages. Do not substitute Guard3, enable routed Scout experts, remove required assertions or silently change resource/precision.

Stop the model

  1. 1. Stop classifier and tunnel

    Press Ctrl+C in the foreground Python terminal. Unset client keys; confirm loopback8996 no longer serves.

    Command
    unset GUARD_SERVICE_KEY

    Expected result: Foreground service stops and loopback8996 no longer responds.

Uninstall

  1. 1. Remove dedicated files

    After confirming the path and preserving wanted diagnostics, remove only this walkthrough directory. Shared apt packages remain.

    Command
    rm -r -- "$HOME/llama-guard4-hosting"

    Expected result: Dedicated weights, venv, wrapper, template/API metadata, requests/responses and private key are removed.

Sources and verification

Sources checked Oct 16, 2026. Verification source

Compare this configuration
Cloud serverDocumented setupSources checked Oct 16, 2026

Self-host Llama Guard 4 image-and-text input classification on an AWS CPU VM

Classify one image plus text using the exact public Unsloth Llama Guard 4 snapshot, Meta classification template and native dense Transformers CPU FP32 path. A reader-authored private endpoint returns safe/unsafe and 13-category labels. One request, 4,096 total tokens and a 32-token greedy check. Fit, speed and classifier accuracy remain unmeasured.

Hardware
AWS r7i.2xlarge, 64 GiB RAM, Ubuntu x86_64
Runtime
Native dense Llama Guard 4 CPU classifier with reader-authored private endpoint Python 3.12; Torch 2.6.0+cpu; TorchVision 0.21.0+cpu; Transformers 4.57.6; FP32 eager attention · CPU
Model format
safetensors · Full native BF16 artifact explicitly loaded as CPU FP32 · No quantization; original BF16 snapshot converted to FP32 on CPU
Workload
4,096 token context · 1 concurrent

Based on source documentation; this setup has not been executed by OpenTools. Memory: unknown. No compatible measurement available.

Read the complete setup guide

Before you start

  • Use an existing authorized Ubuntu 24.04 x86_64 r7i.2xlarge in us-east-1: eight vCPUs, 64 GiB RAM and an 80 GiB gp3 root disk. Existing SSH must restrict port 22 to your IP; keep public 8996 closed. Confirm current quote, quota and capacity before billable provisioning.
  • Use the exact independently public Unsloth snapshot, native Meta classifier template and pinned CPU Python packages. Meta raw checkpoint files remain manually gated; no credential, native download approval or exact byte equivalence is inferred.
  • Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.
  • The fixed single-user image-and-text input classifier is not a general assistant or a guarantee that content is safe. Model labels can be wrong; evaluate your intended policy/workload before relying on results.

Exact model and requirements

Artifact:
Unsloth (public snapshot); Meta (native classifier) / Public Unsloth Llama-Guard-4-12B full five-shard BF16 snapshot · checkpoint unsloth/Llama-Guard-4-12B
Publisher revision:
07ebbb7bdc44fb45bf710a9a69a82c088085f0c8
Artifact digest:
No publisher single-file digest for this multi-file snapshot. Mandatory recipe verifies all five weight SHA256s and every required auxiliary; no index hash is called a whole-weight digest.
Download size:
22.35 GiB
Memory requirement (unknown):
Unknown — No measured full CPU peak for this 12B dense model loaded FP32, native vision encoder and 4K bounded classifier workload.
System RAM / disk:
Unknown / Unknown
Placement:
single device. One CPU host, no tensor or pipeline sharding. Entire dense text model, integrated vision encoder and projector stay on CPU. No GPU, disk offload, device_map or active-expert weight reduction.
KV cache:
FP32 native attention K/V with author-selected dynamic cache
Workload:
4,096 token context; Unknown; Unknown; concurrency 1; batch 1; cache unknown; repetitions Unknown.
Tokenizer:
Pinned public Llama Guard 4 tokenizer plus Meta classifier template from revision API · Public Unsloth snapshot and Meta native classifier template, independently pinned in artifacts and download steps
Sampling / reasoning:
Greedy do_sample=False; author max_new_tokens 32 and repetition_penalty 1.0. Native generation config supplies EOS IDs and pad token. Dynamic rather than native static cache avoids allocating the architectural maximum; actual memory remains unknown. Safety classifier generates label text, not chat answers or free reasoning. Fixed native policy: 13 image categories S1–S13. One user input only; system/assistant history, response filtering, category customization and tool execution are not implemented.
Runtime prerequisites:
Ubuntu 24.04 x86_64; See prerequisites above.

Official artifact · License

Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.

  • All 24,002,322,024 original weight bytes load. FP32 doubles BF16 weight storage in memory before cache, compute/vision buffers and OS; exact startup and peak remain unknown.
  • The classifier is dense after pruning; no Scout routed-expert or active-parameter memory discount applies. 64 GiB RAM, 80 GiB disk and eight threads are planning allocations, not confirmed fit/minima.

One-time setup and hardware

hardware
Not applicable — AWS hardware acquisition is included in compute rental; no purchased GPU required. Any separate hardware cost is not applicable.
AWS hardware acquisition is included in compute rental; no purchased GPU required. Any separate hardware cost is not applicable. Tax: unknown.
setup
Unknown — Initial provisioning/build time and labor cost are unknown.
Initial provisioning/build time and labor cost are unknown. Tax: unknown.

Recurring costs

compute
$0.53 / hour
AWS published us-east-1 Linux On-Demand quote USD 0.5292 per billed instance-hour, no paid preinstalled software. Eight billed hours cost USD 4.2336; 24 hours USD 12.7008 compute. Idle running hours bill. No discount, Spot or reservation assumed. Storage, egress, tax and administration additional; capacity unknown. Region: us-east-1. SKU: r7i.2xlarge Linux On-Demand. Tax: excluded. Price dated Oct 15, 2026. Price source
storage
$0.08 / GB month
Captured us-east-1 gp3 quote USD 0.08 per GB-month, with GB defined as 1024^3 bytes. Selected 80 GiB root volume costs USD 6.40 per full month, prorated by provisioned duration, at baseline 3000 IOPS and 125 MB/s. No provisioned extras assumed; retained snapshots/resources separate. Storage persists after stop; tax excluded. Region: us-east-1. SKU: EBS gp3 baseline 3000 IOPS / 125 MB/s. Tax: excluded. Price dated Oct 16, 2026. Price source
egress
Unknown — Data transfer price, allowances and traffic volume are unknown.
Data transfer price, allowances and traffic volume are unknown. Tax: unknown.
administration
Unknown — Maintenance labor rate and hours are unknown.
Maintenance labor rate and hours are unknown. Tax: unknown.

Install the runtime

  1. 1. Create the exact CPU package environment

    Use the official hash-pinned Torch/TorchVision CPU wheels and native Transformers release. TorchVision supports the native fast image processor, including when a text-only model loads its processor. Transitive/system packages resolve at installation; save versions and stop on conflicts. No installation was executed by the author.

    Command
    sudo apt-get update
    sudo apt-get install -y python3.12 python3.12-venv curl ca-certificates openssl
    mkdir -p "$HOME/llama-guard4-hosting/model"
    cd "$HOME/llama-guard4-hosting"
    python3.12 -m venv .venv
    .venv/bin/python -m pip install 'https://download.pytorch.org/whl/cpu/torch-2.6.0%2Bcpu-cp312-cp312-linux_x86_64.whl#sha256=59e78aa0c690f70734e42670036d6b541930b8eabbaa18d94e090abf14cc4d91' 'https://download-r2.pytorch.org/whl/cpu/torchvision-0.21.0%2Bcpu-cp312-cp312-linux_x86_64.whl#sha256=d6874431e678ba107b60a83f255c33f3755f06bad587b1b919aa514ec325dcd8'
    .venv/bin/python -m pip install 'transformers==4.57.6' pillow
    .venv/bin/python -m pip check
    .venv/bin/python -m pip freeze > resolved-environment.txt

    Expected result: pip hash checks and pip check pass; actual environment is recorded. No CUDA driver or remote model code is used.

Download the model

  1. 1. Download and verify all original derivative weight shards

    Fetch the complete public Unsloth artifact, not gated Meta weight URLs. Verify exact sizes and SHA256s. Existing valid files are reused; partial files cannot replace final files before verification.

    Command
    cd "$HOME/llama-guard4-hosting"
    .venv/bin/python - <<'PYDOWNLOAD'
    import pathlib,json,urllib.request,hashlib
    manifest=json.loads("{\"model-00001-of-00005.safetensors\":{\"bytes\":4997861792,\"sha256\":\"1b3e93a5c09f732537068482a5f00c29a675092f0ae456ebd60043af59c21299\"},\"model-00002-of-00005.safetensors\":{\"bytes\":4981018296,\"sha256\":\"08150644f6be3ae2474a8a9f3290edbc62ac876522217c6bf70ce304ed1351e2\"},\"model-00003-of-00005.safetensors\":{\"bytes\":4991503856,\"sha256\":\"1d30c028733fc776ac18a369d565bb395fa4473aa2317cbedeef1cd216c6b327\"},\"model-00004-of-00005.safetensors\":{\"bytes\":4991503856,\"sha256\":\"ecd9fed60f059359941913c3ade611e8c67a63ba453efbc071de8af007c586e7\"},\"model-00005-of-00005.safetensors\":{\"bytes\":4040434224,\"sha256\":\"57aa2d6a20feb15010f74599e4a4f9f4985cb1b87a975dc6ffc1d34780de7599\"}}")
    for name,meta in manifest.items():
     path=pathlib.Path('model')/name
     def valid(p):
      if not p.exists() or p.stat().st_size!=meta['bytes']:return False
      h=hashlib.sha256()
      with p.open('rb') as f:
       for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
      return h.hexdigest()==meta['sha256']
     if not valid(path):
      tmp=path.with_name(path.name+'.partial')
      with urllib.request.urlopen('https://huggingface.co/unsloth/Llama-Guard-4-12B/resolve/07ebbb7bdc44fb45bf710a9a69a82c088085f0c8/'+name) as response,tmp.open('wb') as out:
       while True:
        b=response.read(8*1024*1024)
        if not b:break
        out.write(b)
      assert valid(tmp),name+' hash/size mismatch';tmp.replace(path)
     assert valid(path);print(name,'OK')
    PYDOWNLOAD

    Expected result: All five original weight shards report OK; total weight bytes 24,002,322,024. No model loads.

  2. 2. Download every required config, tokenizer, processor and license file

    Every required auxiliary is pinned. The independently published Unsloth template adds a BOS prefix; do not use it. The next step extracts the original Meta template from the public metadata API instead.

    Command
    cd "$HOME/llama-guard4-hosting"
    .venv/bin/python - <<'PYDOWNLOAD'
    import pathlib,json,urllib.request,hashlib
    manifest=json.loads("{\"LICENSE\":{\"bytes\":7554,\"sha256\":\"73755cee886613ae3135140882289e0a4955d5f0e90f8b1c1ffc962aa9082917\"},\"USE_POLICY.md\":{\"bytes\":5796,\"sha256\":\"5ae40fe842b87b5773c47cfd25992a496cc09b17cbb246968762f06352d89270\"},\"config.json\":{\"bytes\":2789,\"sha256\":\"344ab345ed1268f17e1d6f7d8eb3947b56ac90ca28834c18c171b64a026563cc\"},\"generation_config.json\":{\"bytes\":222,\"sha256\":\"edf659fdf486cfa5eb4cf127cac2dbac0f24f69439051f5111c66d72e47c31df\"},\"model.safetensors.index.json\":{\"bytes\":95229,\"sha256\":\"cdcb8ad59ccafa69c79df8cd9f109453293c613241dd03e216df01f19538dacd\"},\"preprocessor_config.json\":{\"bytes\":636,\"sha256\":\"11a1b41f43161e324bf8302299bce8d59aba671d1505137d9d01179ae9aeacde\"},\"processor_config.json\":{\"bytes\":128,\"sha256\":\"bfc23f929e2a90ba534426072b2e0288909820f34ae79d8ff3934edda29e1f3a\"},\"special_tokens_map.json\":{\"bytes\":451,\"sha256\":\"3484f80da421ad864f1646dd563b8b772ebc9666c34a19d199d6d481c96d1eda\"},\"tokenizer.json\":{\"bytes\":27948580,\"sha256\":\"22e009b4fcb58eddbabf347e71b9881ea1e6eb72d44e5ea9477c7587df68fd8d\"},\"tokenizer_config.json\":{\"bytes\":235854,\"sha256\":\"13bb887373efca2fea1225d3051500e7b0b215824eeaa5d0ba7c2ce85985ff7f\"}}")
    for name,meta in manifest.items():
     path=pathlib.Path('model')/name
     def valid(p):
      if not p.exists() or p.stat().st_size!=meta['bytes']:return False
      h=hashlib.sha256()
      with p.open('rb') as f:
       for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
      return h.hexdigest()==meta['sha256']
     if not valid(path):
      tmp=path.with_name(path.name+'.partial')
      with urllib.request.urlopen('https://huggingface.co/unsloth/Llama-Guard-4-12B/resolve/07ebbb7bdc44fb45bf710a9a69a82c088085f0c8/'+name) as response,tmp.open('wb') as out:
       while True:
        b=response.read(8*1024*1024)
        if not b:break
        out.write(b)
      assert valid(tmp),name+' hash/size mismatch';tmp.replace(path)
     assert valid(path);print(name,'OK')
    PYDOWNLOAD

    Expected result: All ten native-format derivative auxiliaries report OK. No generic Guard 3/Scout template is substituted.

  3. 3. Extract and verify the native Meta classifier template

    The raw native template is gated, but this revision-specific public API exposes its exact string. Verify the full minimal API response bytes, assert the native revision, encode the template string unchanged and verify its derived digest. The API request expands only immutable sha/config fields, avoiding live download counters.

    Command
    cd "$HOME/llama-guard4-hosting"
    curl --fail --location --output native-template-api.json 'https://huggingface.co/api/models/meta-llama/Llama-Guard-4-12B/revision/87acb4b94e930c3d679e6e7ee9d57e2feab9ea71?expand%5B%5D=sha&expand%5B%5D=config'
    sha256sum --check <<'SHA256'
    08b0234e5e3fdd5efb6abfd32d52840eba4b439bba0b11f203df5eea95d08c80  native-template-api.json
    SHA256
    .venv/bin/python - <<'PYTEMPLATE'
    import pathlib,json,hashlib
    meta=json.loads(pathlib.Path('native-template-api.json').read_text())
    assert meta['sha']=='87acb4b94e930c3d679e6e7ee9d57e2feab9ea71'
    raw=meta['config']['chat_template_jinja'].encode('utf-8')
    assert hashlib.sha256(raw).hexdigest()=='40782d45db7ce0d96b0b2595c698e47603e2d459b0390f5025d974c861c53e3b'
    pathlib.Path('native-chat.jinja').write_bytes(raw)
    assert pathlib.Path('native-chat.jinja').read_bytes()==meta['config']['chat_template_jinja'].encode('utf-8')
    print('Native classifier template extracted verbatim and verified')
    PYTEMPLATE

    Expected result: API file reports OK and native template derivation passes. Exactly one template BOS is used with add_special_tokens=False; no Unsloth extra BOS is added.

Configure

  1. 1. Preserve a private service credential

    Generate a local service key only when absent. Keep it private; this is not a provider credential. An empty existing key must be restored, not silently rotated.

    Command
    cd "$HOME/llama-guard4-hosting"
    umask 077
    if [ ! -e .api-key ]; then openssl rand -hex 32 > .api-key; fi
    test -s .api-key || { echo 'Restore empty key before proceeding'; exit 1; }
    chmod 600 .api-key

    Expected result: A nonempty mode600 key exists; no secret is printed.

  2. 2. Write the private classifier wrapper

    This reader-authored serial HTTPServer implements the documented fixed classifier workflow, not an official Meta server. Native eager attention and dense-layer assertions avoid treating the pruned model as Scout MoE. It checks actual full policy/image token count before generating, and validates native labels without converting invalid output to safe.

    Command
    cd "$HOME/llama-guard4-hosting"
    cat > guard_server.py <<'PYSERVER'
    """Reader-authored private educational classifier, not an official Meta server."""
    import base64,hmac,io,json,os,re
    from http.server import BaseHTTPRequestHandler,HTTPServer
    
    def check_budget(count,limit):
        if count>4032 or count+limit>4096: raise ValueError('input_or_budget')
    
    def parse_label(raw,image_mode):
        raw=raw.strip()
        if raw=='safe': return {'label':'safe','categories':[]}
        match=re.fullmatch(r'unsafe\s*\n\s*(S[0-9]+(?:\s*,\s*S[0-9]+)*)',raw)
        if not match: raise ValueError('invalid_classifier_output')
        keys=[x.strip() for x in match[1].split(',')]
        if len(set(keys))!=len(keys) or any(k not in {'S'+str(i) for i in range(1,14 if image_mode else 15)} for k in keys): raise ValueError('invalid_classifier_output')
        return {'label':'unsafe','categories':keys}
    
    def handler_factory(generate,key,image_mode):
        class Handler(BaseHTTPRequestHandler):
            protocol_version='HTTP/1.0'
            def setup(self):
                super().setup();self.connection.settimeout(10)
            def log_message(self,*args): pass
            def reply(self,status,data):
                body=json.dumps(data,ensure_ascii=False).encode();self.send_response(status)
                self.send_header('Content-Type','application/json; charset=utf-8');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
            def auth(self): return hmac.compare_digest(self.headers.get('Authorization','').encode(),('Bearer '+key).encode())
            def do_GET(self):
                if not self.auth(): return self.reply(401,{'error':'unauthorized'})
                self.reply(200,{'status':'ready'}) if self.path=='/health' else self.reply(404,{'error':'not_found'})
            def do_POST(self):
                if not self.auth(): return self.reply(401,{'error':'unauthorized'})
                if self.path!='/v1/guard': return self.reply(404,{'error':'not_found'})
                if self.headers.get('Transfer-Encoding') is not None: return self.reply(400,{'error':'unsupported_transfer_encoding'})
                if self.headers.get_content_type()!='application/json': return self.reply(415,{'error':'json_required'})
                lengths=self.headers.get_all('Content-Length',[])
                if len(lengths)!=1 or not lengths[0] or not all('0'<=c<='9' for c in lengths[0]): return self.reply(411,{'error':'content_length_required'})
                if len(lengths[0])>6: return self.reply(413,{'error':'body_limit'})
                n=int(lengths[0])
                if not 1<=n<=360000: return self.reply(413,{'error':'body_limit'})
                try:
                    raw=self.rfile.read(n)
                    if len(raw)!=n: return self.reply(400,{'error':'incomplete_body'})
                    data=json.loads(raw)
                except (ValueError,UnicodeError,TimeoutError): return self.reply(400,{'error':'invalid_json'})
                fields={'text','max_new_tokens'}|({'image_base64'} if image_mode else set())
                if type(data)!=dict or set(data)!=fields: return self.reply(400,{'error':'invalid_fields'})
                if type(data['text'])!=str or not data['text'].strip() or type(data['max_new_tokens'])!=int or not 1<=data['max_new_tokens']<=64: return self.reply(400,{'error':'invalid_fields'})
                try: text_size=len(data['text'].encode('utf-8'))
                except UnicodeError: return self.reply(400,{'error':'invalid_text'})
                if text_size>2048: return self.reply(400,{'error':'invalid_text'})
                image=None
                if image_mode:
                    if type(data['image_base64'])!=str or len(data['image_base64'])>349528: return self.reply(400,{'error':'invalid_image'})
                    try: image=base64.b64decode(data['image_base64'],validate=True)
                    except ValueError: return self.reply(400,{'error':'invalid_image'})
                    if not 1<=len(image)<=262144: return self.reply(400,{'error':'invalid_image'})
                try: result=generate(data['text'],data['max_new_tokens'],image)
                except ValueError: return self.reply(422,{'error':'input_budget_or_classifier_format'})
                except Exception: return self.reply(500,{'error':'classification_failed'})
                self.reply(200,result)
        return Handler
    
    def main():
        import warnings,torch
        from PIL import Image
        from transformers import AutoProcessor,Llama4ForConditionalGeneration
        image_mode=os.environ.get('GUARD_IMAGE_MODE')=='1'
        key=open('.api-key').read().strip()
        if len(key)!=64 or any(c not in '0123456789abcdef' for c in key): raise SystemExit('Invalid private key')
        torch.set_num_threads(8)
        processor=AutoProcessor.from_pretrained('./model',local_files_only=True,trust_remote_code=False)
        processor.chat_template=open('native-chat.jinja').read()
        model=Llama4ForConditionalGeneration.from_pretrained('./model',local_files_only=True,trust_remote_code=False,dtype=torch.float32,attn_implementation='eager').to('cpu').eval()
        cfg=model.config.text_config
        assert cfg.moe_layers==[] and cfg.num_local_experts==0 and cfg.num_hidden_layers==48 and cfg.hidden_size==5120
        assert all(not layer.is_moe_layer for layer in model.language_model.model.layers)
        assert next(model.parameters()).dtype==torch.float32
        Image.MAX_IMAGE_PIXELS=4194304
        warnings.simplefilter('error',Image.DecompressionBombWarning)
        def generate(text,limit,image):
            content=[];images=None
            if image is not None:
                try:
                    with Image.open(io.BytesIO(image)) as source:
                        if source.format not in ('PNG','JPEG') or not 1<=source.width<=2048 or not 1<=source.height<=2048: raise ValueError('image_bounds')
                        images=[source.convert('RGB')]
                except (OSError,Image.DecompressionBombError,Image.DecompressionBombWarning) as error: raise ValueError('image_decode') from error
                content.append({'type':'image'})
            content.append({'type':'text','text':text})
            prompt=processor.apply_chat_template([{'role':'user','content':content}],tokenize=False,add_generation_prompt=True,excluded_category_keys=[])
            inputs=processor(text=[prompt],images=images,max_patches=1,add_special_tokens=False,return_tensors='pt')
            count=inputs['input_ids'].shape[-1];check_budget(count,limit)
            assert inputs['input_ids'][0,0].item()==processor.tokenizer.bos_token_id
            with torch.inference_mode():
                out=model.generate(**inputs,max_new_tokens=limit,do_sample=False,repetition_penalty=1.0,cache_implementation='dynamic',pad_token_id=processor.tokenizer.pad_token_id)
            new=out[0,count:];raw=processor.tokenizer.decode(new,skip_special_tokens=True).strip()
            parsed=parse_label(raw,image_mode)
            if len(new)==limit: raise ValueError('classifier_output_cap')
            return {**parsed,'raw_label':raw,'input_tokens':count,'output_tokens':len(new),'policy_categories':13 if image_mode else 14}
        HTTPServer(('127.0.0.1',8996),handler_factory(generate,key,image_mode)).serve_forever()
    if __name__=='__main__': main()
    PYSERVER
    .venv/bin/python -m py_compile guard_server.py

    Expected result: Syntax check succeeds. Wrapper bytes match the source shown; py_compile does not import the model.

Start the model

  1. 1. Start the single-image input classifier

    Run in a foreground terminal. Loads all local weights and integrated vision components in CPU FP32 with eager attention. The exact native template replaces processor defaults. One sequence is served at a time; no generation deadline or public-server resilience is claimed.

    Command
    cd "$HOME/llama-guard4-hosting"
    GUARD_IMAGE_MODE=1 .venv/bin/python guard_server.py

    Expected result: After successful startup, authenticated health reports ready. Stop on model/tokenizer/dense-layer/import/RAM errors. Actual startup has not been executed here.

Connect to your endpoint

http://127.0.0.1:8996/v1/guard

Server loopback only. For a remote client use existing SSH: ssh -N -L 8996:127.0.0.1:8996 USER@VM_IP. Keep public8996 closed. The documented verification reads the private key on the VM.

Access: loopback. Reader-generated Bearer key protects health and classifier routes. Request fields are text and max_new_tokens; image_base64 is additionally required in this image mode. Response fields are label, categories, raw_label, input_tokens, output_tokens and policy_categories. No chat roles, arbitrary URL fetching or provider API is exposed.

Verify the setup

  1. 1. Verify readiness, native label response and authentication

    Run in a second terminal on the same desktop or VM SSH shell. The manually inspected publisher diagram contains Attention/FFN boxes, arrows and a blue dense-feedforward box. Under the fixed image policy the expected smoke label is safe; this is a criterion, not an observed prediction or accuracy claim. No image-description answer should be generated. One PNG/JPEG up to262144 bytes and2048 by2048 pixels is allowed. Native max_patches=1 yields one336-square tile without extra global tile, nominally144 patch placeholders plus markers; actual full input is counted and capped. Accept a complete parsed label only; invalid/empty output, cap exhaustion, context error or unexpected category fails this check.

    Command
    cd "$HOME/llama-guard4-hosting"
    curl --fail --location --output fixture.png 'https://raw.githubusercontent.com/meta-llama/PurpleLlama/d934ea285d124d81c10f7e15a06a1e1f74eff2c3/Llama-Guard4/12B/llama_guard_4_12b_after_pruning.png'
    sha256sum --check <<'SHA256'
    2d5033ef706bf52d4b7ff8a2f76bd211bbdb55ddc791679a9b6968150ebb33ed  fixture.png
    SHA256
    .venv/bin/python - <<'PYREQUEST'
    import pathlib,json,base64,hashlib
    raw=pathlib.Path('fixture.png').read_bytes()
    assert len(raw)==41348 and hashlib.sha256(raw).hexdigest()=='2d5033ef706bf52d4b7ff8a2f76bd211bbdb55ddc791679a9b6968150ebb33ed'
    data={'text':'Please describe the diagram.','max_new_tokens':32,'image_base64':base64.b64encode(raw).decode()}
    pathlib.Path('guard-request.json').write_text(json.dumps(data))
    PYREQUEST
    GUARD_SERVICE_KEY="$(cat .api-key)"
    curl --fail http://127.0.0.1:8996/health -H "Authorization: Bearer $GUARD_SERVICE_KEY"
    curl --fail http://127.0.0.1:8996/v1/guard -H "Authorization: Bearer $GUARD_SERVICE_KEY" -H 'Content-Type: application/json' --data-binary @guard-request.json --output guard-response.json
    cat guard-response.json
    .venv/bin/python - <<'PYRESULT'
    import json
    r=json.load(open('guard-response.json'))
    assert r['label']=='safe' and r['categories']==[] and r['policy_categories']==13
    assert 1<=r['output_tokens']<32 and r['input_tokens']+r['output_tokens']<=4096
    print('Expected native safe label and token-budget checks passed; not a general safety guarantee')
    PYRESULT
    curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8996/health
    unset GUARD_SERVICE_KEY

    Expected result: Authorized health returns ready; classification returns safe, empty categories and native policy count 13. Missing key returns401. Exact raw label text/token counts are unknown; no inference result is claimed.

Performance evidence

No compatible measurement available. Documented support and estimated memory do not establish response speed.

Limits and troubleshooting

  • Documented only: no weights, packages, model imports, installation, build or inference executed. Full fit, latency, throughput and classifier accuracy remain unknown.
  • Meta publisher license and the public Unsloth artifact LICENSE are byte-identical Llama 4 Community License text. This is restricted open weights, not Apache or an unrestricted open-source grant. Comply with incorporated acceptable-use policy, license copies/notices, Built with Llama attribution, applicable redistribution/model-naming obligations and the 700-million-MAU commercial-license condition. Native Meta access is manually gated; no approval or native-file access is claimed. The separately public Unsloth snapshot is used on its own pinned bytes; exact upstream conversion/weight equivalence is unknown. Read applicable terms before use; no legal clearance or safety guarantee is provided. The incorporated use policy withholds Section 1(a) rights for multimodal models from individuals domiciled in the European Union and companies whose principal place of business is in the European Union. Its stated exception covers end users of a product or service incorporating such multimodal models. This guide loads the integrated multimodal checkpoint in both text and image modes; a text-only request or US cloud region does not remove this condition. Determine whether the grant and stated exception cover your use before proceeding; no eligibility determination or legal clearance is asserted.
  • The public derivative has the same five shard sizes as the gated native listing, but native LFS digests are redacted. That does not establish byte equivalence or an exact upstream conversion revision. All runnable derivative bytes are pinned independently.
  • The exact native policy template is extracted from a revision-specific public API; its full API bytes and derived UTF-8 string are verified. Mirror template adds an extra BOS prefix and is deliberately not used. add_special_tokens=False prevents automatic extra BOS.
  • Native Guard4 is dense after pruning:48 layers, hidden5120,40Q/8KV heads, no routed experts, empty moe_layers. Transformers uses a dense MLP path; eager attention is explicitly selected for text and vision. No Guard3 or generic Scout runtime behavior is assumed.
  • Fixed native template has13 image categories and14 text categories; S14 Code Interpreter Abuse is text-only. Parser rejects unexpected/duplicate category IDs, invalid/empty labels and cap exhaustion. A valid format does not establish a correct prediction.
  • Only one user input is classified. Response classification, multi-turn parity/assistant history, category customization, multilingual performance, multi-image inputs, full context and other runtimes/devices remain separate unqualified useful scopes.
  • The reader-authored endpoint is serial and private: authenticated health/classification,360000-byte body limit, strict fields/types,10-second socket read timeout, at most2048 UTF-8 text bytes, actual full input<=4032 and input+requested output<=4096. Requests allow1–64 new tokens; smoke uses32. No generation timeout, TLS/public hardening or calibrated probability is provided.
  • Image mode accepts one validated-base64 PNG/JPEG up to262144 decoded bytes and2048 by2048 pixels. Native max_patches1 resizes to one336-square tile; actual rendered policy/image/text tokens are checked before generation. Text mode accepts no image field.
  • Full FP32 weights, vision components, cache, buffers and OS share system RAM.64 GiB RAM,80 GiB disk and eight threads are allocations, not measured minima or confirmed fit.
  • Guard4 labels can have false positives and false negatives, and policy alignment may differ from your intended use. A safe label is not a universal assurance; the narrow benign fixture is not a quality benchmark.
  • System and transitive packages resolve at installation. Exact Torch/TorchVision wheel hashes and Transformers version are supplied, but target Python3.12 model/processor startup compatibility remains unexecuted.
  • Publisher diagram is used only in the image guide from its exact official source URL; retain Meta attribution and applicable Llama4 license terms. No broader image-rights clearance is claimed.
  • Two modality pairs do not establish exhaustive model coverage. Original cloud quote dates and unknown egress/tax/admin are retained; local purchase/power remain unknown.
401 or connection refused
Check foreground startup and matching private key. For cloud check existing SSH tunnel and keep public8996 closed.
400,411,413,415 or422 response
Use exact mode-specific fields, JSON media type, one ASCII Content-Length and bounded text/image bytes. Check actual policy+image input tokens and requested generation cap. Invalid native label/category or exhausted cap is a failed classification, never an automatic safe result.
Unexpected label or category
Inspect raw_label and the native fixed policy. S14 exists only for text. Record false positive/negative behavior; do not reinterpret model labels as guaranteed safe or substitute general chat output.
Model/tokenizer/dense assertion or memory error
Stop. Verify all independent derivative hashes, native API/template derivation and exact CPU packages. Do not substitute Guard3, enable routed Scout experts, remove required assertions or silently change resource/precision.

Stop the model

  1. 1. Stop classifier and tunnel

    Press Ctrl+C in the foreground Python terminal. Unset client keys; close any SSH tunnel with Ctrl+C. Stopping Python alone does not stop EC2 billing.

    Command
    unset GUARD_SERVICE_KEY

    Expected result: Foreground service stops and loopback8996 no longer responds.

Uninstall

  1. 1. Remove dedicated files

    After confirming the path and preserving wanted diagnostics, remove only this walkthrough directory. Shared apt packages remain.

    Command
    rm -r -- "$HOME/llama-guard4-hosting"

    Expected result: Dedicated weights, venv, wrapper, template/API metadata, requests/responses and private key are removed.

Shut down cloud resources

  1. 1. End cloud billing resources

    In EC2 us-east-1, stop for later reuse or terminate this exact VM. Review Delete on termination for its root volume. Delete unwanted detached EBS volumes, snapshots and reserved/Elastic/public IP resources. Stopped VM storage and retained resources may still bill. Check Bills/Cost Explorer later for final usage.

    Expected result: Exact instance is stopped/terminated as intended; no unwanted attached/retained billed resources remain. Instance compute stops only after its lifecycle transition, not when the Python classifier stops.

Sources and verification

Sources checked Oct 16, 2026. Verification source

Compare this configuration

Benchmarks

Performance scores for Llama Guard 4 12B across standard benchmarks.

LG4 English output-filter F1Meta
61%
LG4 multilingual output-filter F1Meta
51%
LG4 single-image output-filter F1Meta
38%
LG4 multi-image output-filter F1Meta
52%

Pricing

Token pricing for Llama Guard 4 12B API usage.

Input Tokens

$0.18/M

per million tokens

Output Tokens

$0.18/M

per million tokens

Meta logo
Metatechnology company

Build the future of human connection and the technology that makes it possible

5 Tools8 ModelsFounded 2004Menlo Park, California, United States
View full profile

Tools by Meta

Other AI tools from the same organization.

AI Models by Meta

AI models from the same organization.

ModelContext WindowPrice (In / Out per M)
Muse Spark 1.1Current1.0M$1.25 / $4.25
DINOv3Current---- / --
Llama 4 MaverickCurrent1.0M$0.15 / $0.60
Llama 4 ScoutCurrent328K$0.08 / $0.30
Llama Guard 3 8BCurrent131K$0.48 / $0.03
Segment Anything ModelCurrent---- / --

Related News

Latest coverage and updates.