CompVis logo

Stable Diffusion

Stable Diffusionvv1Current
byCompVisCompVis(open source)
Released August 22, 2022
Context--
CategoryImage Model

About Stable Diffusion

Stable Diffusion is a latent text-to-image diffusion model from CompVis, developed with compute support from Stability AI and support from LAION. The v1 model generates and modifies images from text prompts using a latent diffusion architecture and a frozen CLIP ViT-L/14 text encoder.

Capabilities

text to imageimage generationimage to imageresearch

Input Modalities

textimage

Output Modalities

image

Technical Details

API Identifier
CompVis/stable-diffusion-v1
Category
Image Model

Tags

text-to-imagediffusionlatent-diffusionimage-generationopen-weightsresearchcreative-ai

Run this model yourself

Local and cloud setup for Stable Diffusion, with exact configurations, sources and clear evidence limits.

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

Run original Stable Diffusion v1-4 text-to-image on a local CPU

Generate one original 512 by512 watercolor scene with the pinned CompVis v1-4 native Diffusers pipeline, CPU FP32 and the native safety checker. The private fixed-fixture endpoint verifies all selected assets, refuses prompt truncation and returns a PNG for manual inspection. RAM allocation is a planning choice; fit, speed and scene quality are unmeasured.

Hardware
Intel Core i5-12400 desktop, 4 inference threads, 32 GiB RAM
Runtime
Native CompVis v1-4 Diffusers CPU private image harness Diffusers0.35.1; Transformers4.57.6; Torch2.6.0+cpu; Python3.12; Hub0.36.0; Safetensors0.6.2; Accelerate1.11.0; NumPy2.2.3; Pillow11.1.0 · CPU
Model format
safetensors · FP32 native safetensors · None; FP32
Workload
77 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 Ubuntu 24.04 x86_64 Intel CPU environment with Python 3.12, 32 GiB RAM and 40 GiB available disk allocated for this recipe; fit, peak memory, latency and image quality remain unmeasured.
  • Read the pinned CreativeML OpenRAIL-M license and model card before using the model. Comply with Attachment A and paragraph 5 for all usage and outputs. Remote distribution additionally requires enforceable downstream terms, license copy and notices; a private bearer key is not a license-compliance mechanism.
  • Use a fresh isolated venv. Downloads access public official model/package sources; no Hugging Face login, API token or paid endpoint is required by the captured public metadata. Recheck access if the publisher changes it.
  • The reader-authored single-request HTTP server is a private educational harness, not a production server. Port 8997 must remain on loopback; do not expose it through a firewall, proxy or public tunnel.

Exact model and requirements

Artifact:
CompVis / Stable Diffusion v1-4 native Diffusers composition · checkpoint CompVis/stable-diffusion-v1-4
Publisher revision:
133a221b8aa7292a167afc5127cb63fb5005638b
Artifact digest:
Composite snapshot has no single publisher whole-artifact digest. All 15 selected files are individually pinned and verified.
Download size:
5.1 GiB
Memory requirement (unknown):
Unknown — No measured full-process peak for this exact CPU float32 model, image activation/decoder state and dependencies.
System RAM / disk:
Unknown / Unknown
Placement:
single device. One CPU process, no tensor/pipeline sharding. All selected modules explicitly on CPU FP32; no GPU, disk offload or remote inference.
KV cache:
Diffusion denoising with CLIP conditioning; no autoregressive text KV cache.
Workload:
77 token context; Unknown; Not applicable; concurrency 1; batch 1; cache cold; repetitions Not applicable.
Tokenizer:
Native CLIPTokenizer for CompVis v1-4 · 133a221b8aa7292a167afc5127cb63fb5005638b
Sampling / reasoning:
PNDMScheduler from exact snapshot;512 by512, one image,50 requested inference steps, guidance 7.5, negative prompt empty, CPU generator seed 12345. No text decoding sampler. Not applicable: text-conditioned latent diffusion; no chat template or reasoning output.
Runtime prerequisites:
Ubuntu24.04 x86_64; See prerequisites above.

Official artifact · License

CreativeML OpenRAIL-M dated August 22, 2022. Conditional model and complementary-material copyright/patent grants. Attachment A use restrictions apply to use and outputs. Section 4 explicitly permits remote hosting but requires enforceable downstream use restrictions and notice, license copy, retained notices, and prominent modified-file notices. Require all users to comply with paragraph 5. No trademark grant, safety guarantee or blanket output-rights clearance. This bounded private research guide does not implement a third-party public hosting agreement.

  • 32 GiB RAM and 40 GiB disk are allocated host resources, not measured model requirements.
  • The four weight files total 5,481,058,519 bytes. Runtime copies, activations, safety checker and scheduler memory mean file size is not peak RAM or proof of fit.
  • No target install or inference, peak memory or performance was measured.

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 40 GiB free-disk walkthrough allocation is an author choice, not a measured requirement.
Incremental cost of local disk capacity is unknown. The 40 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. Install the explicitly pinned native CPU pipeline

    Install core package versions and their normal declared dependencies without stripping dependencies. Save the actual transitive resolution and run pip check. The native selected path uses CLIP text/image processing and PNDM; no training, export, all-extra or optional torchvision stack is selected. Package resolution and target compatibility are documented, not executed here.

    Command
    set -e
    sudo apt-get update
    sudo apt-get install -y python3.12 python3.12-venv curl ca-certificates openssl
    mkdir -p "$HOME/sd-v14-image/models"
    cd "$HOME/sd-v14-image"
    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'
    .venv/bin/python -m pip install 'diffusers==0.35.1' 'transformers==4.57.6' 'huggingface-hub==0.36.0' 'safetensors==0.6.2' 'accelerate==1.11.0' 'numpy==2.2.3' 'Pillow==11.1.0'
    .venv/bin/python -m pip check
    .venv/bin/python -m pip freeze > resolved-environment.txt
    .venv/bin/python - <<'PYVERS'
    import importlib.metadata as m
    for k,v in {'torch':'2.6.0+cpu','diffusers':'0.35.1','transformers':'4.57.6','huggingface-hub':'0.36.0','safetensors':'0.6.2','accelerate':'1.11.0','numpy':'2.2.3','Pillow':'11.1.0'}.items():
        assert m.version(k)==v,(k,m.version(k))
    try: m.version('torchvision')
    except m.PackageNotFoundError: pass
    else: raise RuntimeError('Use a fresh venv without optional torchvision')
    print('core versions verified; resolved transitive environment saved')
    PYVERS

    Expected result: Pinned core versions match, ordinary dependency resolution and pip check pass; resolved-environment.txt records the actual environment.

Download the model

  1. 1. Download and verify the complete selected native composition

    Four FP32 safetensors contain model weights. Eleven model, tokenizer, scheduler and image-processor text files complete the selected composition. The pinned snapshot metadata provides individual weight sizes and SHA digests; text digests are derived from archived raw bytes. Each stream must match size and digest before replacement. Retain the exact license. No pickle fallback or alternative checkpoint is selected.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    cat > assets.json <<'ASSETS'
    [
      {
        "path": "safety_checker/model.safetensors",
        "bytes": 1215981830,
        "sha256": "9d6a233ff6fd5ccb9f76fd99618d73369c52dd3d8222376384d0e601911089e8"
      },
      {
        "path": "text_encoder/model.safetensors",
        "bytes": 492265879,
        "sha256": "7b3a12df205cb3c74dd4eae4354d93f606ae6b3bc29d5d06fd97921cb9ad8a81"
      },
      {
        "path": "unet/diffusion_pytorch_model.safetensors",
        "bytes": 3438167534,
        "sha256": "145a07e0f05ec5bbe6e2e9faf608bdb311caf708895cac8c8ed713c59864e1e8"
      },
      {
        "path": "vae/diffusion_pytorch_model.safetensors",
        "bytes": 334643276,
        "sha256": "a2b5134f4dbc140d9c11f11cba3233099e00af40f262f136c691fb7d38d2194c"
      },
      {
        "path": "model_index.json",
        "bytes": 541,
        "sha256": "c7cc314014486aa2f7f17ab8f90197fe0412c818cdefb9e15601ae58752b5001"
      },
      {
        "path": "feature_extractor/preprocessor_config.json",
        "bytes": 342,
        "sha256": "2a1da83b5e1032aaeef397552ddb408dca0d8cd1dc58f61bf6abf38d6f33a0a2"
      },
      {
        "path": "safety_checker/config.json",
        "bytes": 4556,
        "sha256": "a069f3ab23e39f3d608b220d9ae6067a94e43405557e575cf7f98d7e8d2a255c"
      },
      {
        "path": "scheduler/scheduler_config.json",
        "bytes": 313,
        "sha256": "8335df29b53da12e9aeca35b1c2e60d88b23eae4cc5ad3d07efdcd7f003cc343"
      },
      {
        "path": "text_encoder/config.json",
        "bytes": 592,
        "sha256": "aa210e6d6abd239a466af57a1dadb62d5ced63295064d295a549e08a6c4a2020"
      },
      {
        "path": "tokenizer/merges.txt",
        "bytes": 524619,
        "sha256": "9fd691f7c8039210e0fced15865466c65820d09b63988b0174bfe25de299051a"
      },
      {
        "path": "tokenizer/special_tokens_map.json",
        "bytes": 472,
        "sha256": "c4864a9376a8401918425bed71fc14fc0e81f9b59ec45c1cf96cccb2df508eac"
      },
      {
        "path": "tokenizer/tokenizer_config.json",
        "bytes": 806,
        "sha256": "00439066fcba73de57644cf41e4e3b9f2dbb09d7f3fc2005898ba52399045882"
      },
      {
        "path": "tokenizer/vocab.json",
        "bytes": 1059962,
        "sha256": "e089ad92ba36837a0d31433e555c8f45fe601ab5c221d4f607ded32d9f7a4349"
      },
      {
        "path": "unet/config.json",
        "bytes": 743,
        "sha256": "d6749baad843798f21da6c2d3dd9d642e5ebb73455ade4763158f5c6d3e95b03"
      },
      {
        "path": "vae/config.json",
        "bytes": 551,
        "sha256": "0e5966d4d52c8077648754ffd2c14ab5e0b26a4bdfa6af1d207c27550fa6d2af"
      }
    ]
    ASSETS
    .venv/bin/python - <<'PYDL'
    import pathlib,json,urllib.request,hashlib,os
    root=pathlib.Path('models');root.mkdir(exist_ok=True)
    for row in json.loads(pathlib.Path('assets.json').read_text()):
        target=root/row['path'];target.parent.mkdir(parents=True,exist_ok=True)
        part=target.with_suffix(target.suffix+'.partial');h=hashlib.sha256();n=0
        url='https://huggingface.co/CompVis/stable-diffusion-v1-4/resolve/133a221b8aa7292a167afc5127cb63fb5005638b/'+row['path']
        with urllib.request.urlopen(url,timeout=60) as src,part.open('wb') as dst:
            for block in iter(lambda:src.read(1048576),b''):h.update(block);n+=len(block);dst.write(block)
        assert n==row['bytes'] and h.hexdigest()==row['sha256'],row['path']
        os.replace(part,target)
    print('15 exact pinned assets verified')
    PYDL
    curl --fail --location 'https://raw.githubusercontent.com/CompVis/stable-diffusion/21f890f9da3cfbeaba8e2ac3c425ee9e998d5229/LICENSE' -o MODEL-LICENSE.txt
    printf '%s  %s\n' 'be351ebe7ac01bcdbb018639aadcfd38f136b7dc3f2a3d4d3a24db51d1b210ef' MODEL-LICENSE.txt | sha256sum --check -

    Expected result: All 15 files and license pass byte/digest checks; failures terminate the block before starting the service.

Configure

  1. 1. Create the private native image harness

    The adapter loads all four native components using safetensors, CPU FP32, eval mode and four empty loading-diagnostic lists. It verifies every asset at each startup. CLIP tokenizes the original fixed prompt with BOS/EOS and without truncation; reject more than 77 positions before the pipeline can truncate. Native safety checker and feature processor remain loaded. The endpoint accepts only the cabin fixture; no arbitrary model, prompts, paths, uploads, URLs, tools or network actions are exposed. This wrapper is reader-authored and not an official CompVis server.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    cat > reader-image-server.py <<'PYSERVER'
    """Reader-authored bounded research endpoint, not an official or production server."""
    import base64, hashlib, hmac, io, json, os, pathlib, re, sys
    from http.server import BaseHTTPRequestHandler, HTTPServer
    PROMPT = 'A watercolor painting of a small red wooden cabin beside a blue lake, pine trees, daylight, no people, no text.'
    PARAMS = {'height':512,'width':512,'num_inference_steps':50,'guidance_scale':7.5,'num_images_per_prompt':1}
    
    def checked_info(value):
        if not isinstance(value,dict) or set(value)!={'missing_keys','unexpected_keys','mismatched_keys','error_msgs'} or any(not isinstance(v,list) or v for v in value.values()):
            raise ValueError('Checkpoint loading diagnostics are not four empty lists')
    
    def verify_assets(root):
        rows=json.loads(pathlib.Path('assets.json').read_text())
        if not isinstance(rows,list) or len(rows)!=15: raise ValueError('asset manifest shape')
        for row in rows:
            rel=row['path']
            if not isinstance(rel,str) or rel.startswith('/') or '..' in pathlib.PurePosixPath(rel).parts: raise ValueError('asset path')
            path=root/rel
            if path.is_symlink() or not path.is_file() or path.stat().st_size!=row['bytes']: raise ValueError('asset size')
            h=hashlib.sha256()
            with path.open('rb') as stream:
                for block in iter(lambda:stream.read(1048576),b''): h.update(block)
            if h.hexdigest()!=row['sha256']: raise ValueError('asset digest')
    
    def native_engine(root):
        os.environ.update(HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_HUB_DISABLE_TELEMETRY='1')
        verify_assets(root)
        import torch
        from transformers import CLIPTextModel, CLIPTokenizer, CLIPImageProcessor
        from diffusers import StableDiffusionPipeline, UNet2DConditionModel, AutoencoderKL, PNDMScheduler
        from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
        torch.set_num_threads(4); torch.set_num_interop_threads(1)
        common={'local_files_only':True,'use_safetensors':True,'torch_dtype':torch.float32,'output_loading_info':True}
        def load(cls,sub):
            model,info=cls.from_pretrained(str(root/sub),**common)
            checked_info(info)
            return model.to('cpu',dtype=torch.float32).eval()
        text=load(CLIPTextModel,'text_encoder'); unet=load(UNet2DConditionModel,'unet')
        vae=load(AutoencoderKL,'vae'); safety=load(StableDiffusionSafetyChecker,'safety_checker')
        tokenizer=CLIPTokenizer.from_pretrained(str(root/'tokenizer'),local_files_only=True)
        ids=tokenizer(PROMPT,add_special_tokens=True,truncation=False)['input_ids']
        if tokenizer.model_max_length!=77 or text.config.max_position_embeddings!=77 or not 2<=len(ids)<=77: raise ValueError('prompt exceeds exact conditioning window')
        processor=CLIPImageProcessor.from_pretrained(str(root/'feature_extractor'),local_files_only=True)
        scheduler=PNDMScheduler.from_pretrained(str(root/'scheduler'),local_files_only=True)
        pipe=StableDiffusionPipeline(vae=vae,text_encoder=text,tokenizer=tokenizer,unet=unet,scheduler=scheduler,safety_checker=safety,feature_extractor=processor,requires_safety_checker=True).to('cpu')
        pipe.set_progress_bar_config(disable=True)
        def run():
            with torch.inference_mode():
                out=pipe(PROMPT,negative_prompt='',generator=torch.Generator(device='cpu').manual_seed(12345),output_type='pil',**PARAMS)
            flags=out.nsfw_content_detected
            if not isinstance(flags,list) or len(flags)!=1 or type(flags[0]) is not bool: raise ValueError('missing checker result')
            if flags[0]: return {'blocked':True}
            if len(out.images)!=1 or out.images[0].size!=(512,512) or out.images[0].mode!='RGB': raise ValueError('native image shape')
            buf=io.BytesIO();out.images[0].save(buf,format='PNG');raw=buf.getvalue()
            if not 8<len(raw)<=2097152 or not raw.startswith(b'\x89PNG\r\n\x1a\n'): raise ValueError('PNG boundary')
            return {'blocked':False,'png_base64':base64.b64encode(raw).decode('ascii'),'sha256':hashlib.sha256(raw).hexdigest(),'width':512,'height':512,'prompt_tokens':len(ids),'seed':12345,'requested_steps':50,'output_text_tokens':None}
        return run,len(ids)
    
    def server(engine,token,prompt_tokens,port=8997):
        if not re.fullmatch(r'[0-9a-f]{64}',token): raise ValueError('invalid private key')
        class Handler(BaseHTTPRequestHandler):
            protocol_version='HTTP/1.0'
            def log_message(self,*args): pass
            def setup(self): super().setup();self.connection.settimeout(15)
            def send(self,status,value):
                data=json.dumps(value,allow_nan=False,separators=(',',':')).encode()
                self.send_response(status);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(data)));self.send_header('Connection','close');self.end_headers();self.wfile.write(data);self.close_connection=True
            def auth(self):
                values=self.headers.get_all('Authorization',[])
                return len(values)==1 and hmac.compare_digest(values[0].encode('utf-8'), ('Bearer '+token).encode('ascii'))
            def do_GET(self):
                if not self.auth(): return self.send(401,{'error':'unauthorized'})
                if self.path!='/health': return self.send(404,{'error':'not_found'})
                return self.send(200,{'ready':True,'context_positions':77,'prompt_tokens':prompt_tokens,'output':'PNG','parameters':PARAMS})
            def do_POST(self):
                if not self.auth(): return self.send(401,{'error':'unauthorized'})
                if self.path!='/v1/image': return self.send(404,{'error':'not_found'})
                lens=self.headers.get_all('Content-Length',[])
                if self.headers.get_all('Transfer-Encoding',[]): return self.send(400,{'error':'framing'})
                if len(lens)!=1 or not re.fullmatch('[0-9]{1,4}',lens[0]): return self.send(411,{'error':'length_required'})
                n=int(lens[0])
                if not 1<=n<=128:return self.send(413,{'error':'body_bound'})
                if self.headers.get_content_type()!='application/json':return self.send(415,{'error':'json_required'})
                try:
                    raw=self.rfile.read(n)
                    if len(raw)!=n: raise ValueError('short body')
                    def unique(pairs):
                        d={}
                        for k,v in pairs:
                            if k in d:raise ValueError('duplicate key')
                            d[k]=v
                        return d
                    value=json.loads(raw,object_pairs_hook=unique,parse_constant=lambda _:(_ for _ in ()).throw(ValueError('constant')))
                    if value!={'fixture':'cabin'}: raise ValueError('fixed fixture only')
                except (ValueError,UnicodeError):return self.send(400,{'error':'invalid_request'})
                try:
                    result=engine()
                    if result=={'blocked':True}:return self.send(422,{'error':'native_checker_flagged','image_returned':False})
                    if not isinstance(result,dict) or result.get('blocked') is not False:raise ValueError('invalid engine result')
                    return self.send(200,result)
                except Exception:return self.send(500,{'error':'native_inference_failed'})
        return HTTPServer(('127.0.0.1',port),Handler)
    
    if __name__=='__main__':
        key=pathlib.Path('server.key').read_text().strip();engine,count=native_engine(pathlib.Path('models').resolve())
        server(engine,key,count).serve_forever()
    PYSERVER

    Expected result: Local adapter source is saved exactly. Review it before use; no model load occurs in this configure step.

Start the model

  1. 1. Start on authenticated loopback

    Keep the existing nonempty secret stable; an empty existing file is an error, not a silent rotation. Startup performs all asset and native load checks before binding. Inspect server.log if startup exits. Native CPU execution may take substantial time; no latency or cancellation guarantee is claimed.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    if [ -e server.pid ]; then echo 'Existing PID record: inspect and stop that process first'; exit 1; fi
    umask 077
    if [ ! -e server.key ]; then openssl rand -hex 32 > server.key; fi
    test -s server.key
    export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_HUB_DISABLE_TELEMETRY=1
    export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4
    nohup .venv/bin/python reader-image-server.py > server.log 2>&1 &
    printf '%s\n' "$!" > server.pid
    printf 'Started PID %s; inspect server.log and authenticated health after model loading\n' "$(cat server.pid)"

    Expected result: A PID record and log appear; health becomes ready only after native loading and prompt validation.

Connect to your endpoint

http://127.0.0.1:8997/v1/image

Only the host loopback interface; single serial request. Health is /health on the same loopback port.

Access: loopback. Bearer token read from server.key; do not print or share it. POST JSON contains fixture with value cabin. Response contains PNG base64, digest, dimensions, actual prompt count, seed and requested scheduler steps. The native checker flag returns 422 without an image. Duplicate keys, oversized bodies and unsupported framing are rejected. No TLS or production inference deadline is provided.

Verify the setup

  1. 1. Check authenticated native readiness

    Run after startup has completed; do not treat an open socket as successful native loading. Health exposes actual prompt count, fixed image parameters and the 77-position conditioning window.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    .venv/bin/python - <<'PYHEALTH'
    import pathlib,urllib.request,json
    key=pathlib.Path('server.key').read_text().strip()
    r=urllib.request.Request('http://127.0.0.1:8997/health',headers={'Authorization':'Bearer '+key})
    with urllib.request.urlopen(r,timeout=60) as response:d=json.load(response)
    assert d['ready'] is True and d['context_positions']==77 and 2<=d['prompt_tokens']<=77
    print(d)
    PYHEALTH

    Expected result: Ready true, actual prompt positions within 77 and the documented fixed image parameters.

  2. 2. Generate and inspect one original synthetic image

    The prompt asks for a watercolor red wooden cabin beside a blue lake, pine trees and daylight, with no people or text. Generation is 512 by512, one image, seed 12345, requested 50 PNDM steps and guidance 7.5. Verify returned PNG digest/shape, then inspect cabin.png visually for those features. Exact pixels, scene correctness and cross-platform reproducibility are not guaranteed. A 422 native checker flag is an observable blocked result; never disable the checker or present a blank image as success. Client timeout does not cancel native inference.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    .venv/bin/python - <<'PYIMAGE'
    import pathlib,urllib.request,json,base64,hashlib,io
    from PIL import Image
    key=pathlib.Path('server.key').read_text().strip()
    r=urllib.request.Request('http://127.0.0.1:8997/v1/image',data=b'{"fixture":"cabin"}',headers={'Authorization':'Bearer '+key,'Content-Type':'application/json'})
    with urllib.request.urlopen(r,timeout=3600) as response:d=json.load(response)
    assert d['blocked'] is False and d['width']==d['height']==512 and d['requested_steps']==50
    assert d['seed']==12345 and 2<=d['prompt_tokens']<=77 and d['output_text_tokens'] is None
    raw=base64.b64decode(d['png_base64'],validate=True)
    assert 8<len(raw)<=2097152 and hashlib.sha256(raw).hexdigest()==d['sha256']
    image=Image.open(io.BytesIO(raw));image.load();assert image.format=='PNG' and image.size==(512,512) and image.mode=='RGB'
    pathlib.Path('cabin.png').write_bytes(raw);print('Verified image bytes; visually inspect cabin.png for the stated cabin/lake/pines prompt.')
    PYIMAGE

    Expected result: Either one verified PNG for manual scene inspection, or a visible checker/native failure requiring investigation. No exact generated image or measured quality is asserted.

  3. 3. Check authentication and fixed request boundary

    These negative checks must fail before inference; they do not generate additional images.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    .venv/bin/python - <<'PYERROR'
    import pathlib,urllib.request,urllib.error,json
    url='http://127.0.0.1:8997';key=pathlib.Path('server.key').read_text().strip()
    for path,body,auth,expected in [('/health',None,False,401),('/v1/image',b'{"fixture":"other"}',True,400)]:
        headers={'Content-Type':'application/json'}
        if auth:headers['Authorization']='Bearer '+key
        try:urllib.request.urlopen(urllib.request.Request(url+path,data=body,headers=headers),timeout=30)
        except urllib.error.HTTPError as e:assert e.code==expected;print(e.code,json.load(e))
        else:raise RuntimeError('Expected error did not occur')
    PYERROR

    Expected result: Unauthenticated health returns 401 and unknown fixture returns 400.

Performance evidence

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

Limits and troubleshooting

  • The77-position limit is CLIP text conditioning including special tokens. Output is an image; pixels,64 by64 latent positions, scheduler evaluations and50 requested steps are not generated text tokens.
  • A fixed seed is a reproducibility aid within an environment, not a cross-version/platform byte guarantee. Native scheduler internals may perform a different number of UNet evaluations than the requested step count.
  • The native safety checker is retained but can miss harmful content or flag benign images. Neither the checker nor this guide guarantees safety, rights clearance or accuracy. Read the publisher model card and full use restrictions.
  • This is one source-qualified v1-4 text-to-image CPU job, not complete v1 family coverage. Other original checkpoints, image-to-image, GPU routes and public-service operational/legal work remain open.
  • No target install, model load, generation, peak memory, fit, throughput, price outcome or visual quality was measured. Four CPU threads are requested through Torch and environment variables; other libraries may have their own behavior.
  • Inference is serial and blocks this simple HTTPServer, including health while busy. Socket/client timeouts do not enforce an inference deadline; stop the process to terminate an unwanted long computation.
Asset checksum, strict loading diagnostics or offline load fails
Stop and inspect the exact asset/path/version. All four diagnostic lists must be empty. Do not ignore missing/mismatched tensors, allow random initialization, use pickle fallback, fetch a mutable checkpoint or turn off offline loading.
Request errors, checker flag or missing scene elements
Confirm the fixed fixture and private key. A native checker flag is a failed/blocked output, not permission to bypass filtering. Visually missing cabin/lake/pines is an unverified semantic result; retain it honestly and investigate without asserting model correctness.
Slow CPU generation, memory exhaustion or health unavailable while busy
This is an unmeasured32 GiB planning allocation. Stop the process if necessary; do not assume aggregate disk/weight size proves memory fit. Serial inference blocks health. Investigate host/process usage before selecting a different qualified configuration.

Stop the model

  1. 1. Stop and verify the recorded service

    Verify PID command identity before sending termination. Preserve logs and generated image if needed.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    if [ -e server.pid ]; then
      pid=$(cat server.pid)
      case "$pid" in ''|*[!0-9]*) echo 'Invalid PID record'; exit 1;; esac
      if kill -0 "$pid" 2>/dev/null; then
        ps -p "$pid" -o args= | grep -F 'reader-image-server.py' >/dev/null || { echo 'PID identity mismatch; inspect manually'; exit 1; }
        kill "$pid"
        for n in 1 2 3 4 5; do kill -0 "$pid" 2>/dev/null || break; sleep 1; done
        if kill -0 "$pid" 2>/dev/null; then echo 'Still running; inspect before further action'; exit 1; fi
      fi
      rm server.pid
    fi

    Expected result: Recorded service exits and PID record is removed; if identity differs or remains running, stop and inspect manually.

Uninstall

  1. 1. Remove only this dedicated environment

    Stop first and preserve any image/logs you want. The command only removes this dedicated directory; do not reuse it for unrelated data. Model license notices must accompany any separately retained distributed model copies.

    Command
    set -e
    cd "$HOME"
    test ! -e "$HOME/sd-v14-image/server.pid"
    rm -r -- "$HOME/sd-v14-image"

    Expected result: The dedicated model files, venv, key, logs and optional generated image are removed.

Sources and verification

Sources checked Oct 16, 2026. Verification source

Compare this configuration
Cloud serverDocumented setupSources checked Oct 16, 2026

Run original Stable Diffusion v1-4 text-to-image on an AWS R7i CPU

Generate one original 512 by512 watercolor scene with the pinned CompVis v1-4 native Diffusers pipeline, CPU FP32 and the native safety checker. The private fixed-fixture endpoint verifies all selected assets, refuses prompt truncation and returns a PNG for manual inspection. RAM allocation is a planning choice; fit, speed and scene quality are unmeasured.

Hardware
AWS r7i.xlarge, 32 GiB RAM, Ubuntu x86_64
Runtime
Native CompVis v1-4 Diffusers CPU private image harness Diffusers0.35.1; Transformers4.57.6; Torch2.6.0+cpu; Python3.12; Hub0.36.0; Safetensors0.6.2; Accelerate1.11.0; NumPy2.2.3; Pillow11.1.0 · CPU
Model format
safetensors · FP32 native safetensors · None; FP32
Workload
77 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 AWS r7i.xlarge Ubuntu 24.04 x86_64 instance in the source-dated us-east-1 scenario, with 4 vCPU,32 GiB RAM and 40 GiB gp3 allocation. Provisioning is a reader action outside this documented research. Fit, peak memory, speed and quality remain unmeasured.
  • Read the pinned CreativeML OpenRAIL-M license and model card before using the model. Comply with Attachment A and paragraph 5 for all usage and outputs. Remote distribution additionally requires enforceable downstream terms, license copy and notices; a private bearer key is not a license-compliance mechanism.
  • Use a fresh isolated venv. Downloads access public official model/package sources; no Hugging Face login, API token or paid endpoint is required by the captured public metadata. Recheck access if the publisher changes it.
  • The reader-authored single-request HTTP server is a private educational harness, not a production server. Port 8997 must remain on loopback; do not expose it through a firewall, proxy or public tunnel.
  • Keep inbound 8997 closed. Use the already configured SSH identity and an SSH tunnel; do not paste credentials into commands. AWS compute, persistent storage, addresses and egress can remain billable independently.

Exact model and requirements

Artifact:
CompVis / Stable Diffusion v1-4 native Diffusers composition · checkpoint CompVis/stable-diffusion-v1-4
Publisher revision:
133a221b8aa7292a167afc5127cb63fb5005638b
Artifact digest:
Composite snapshot has no single publisher whole-artifact digest. All 15 selected files are individually pinned and verified.
Download size:
5.1 GiB
Memory requirement (unknown):
Unknown — No measured full-process peak for this exact CPU float32 model, image activation/decoder state and dependencies.
System RAM / disk:
Unknown / Unknown
Placement:
single device. One CPU process, no tensor/pipeline sharding. All selected modules explicitly on CPU FP32; no GPU, disk offload or remote inference.
KV cache:
Diffusion denoising with CLIP conditioning; no autoregressive text KV cache.
Workload:
77 token context; Unknown; Not applicable; concurrency 1; batch 1; cache cold; repetitions Not applicable.
Tokenizer:
Native CLIPTokenizer for CompVis v1-4 · 133a221b8aa7292a167afc5127cb63fb5005638b
Sampling / reasoning:
PNDMScheduler from exact snapshot;512 by512, one image,50 requested inference steps, guidance 7.5, negative prompt empty, CPU generator seed 12345. No text decoding sampler. Not applicable: text-conditioned latent diffusion; no chat template or reasoning output.
Runtime prerequisites:
Ubuntu24.04 x86_64; See prerequisites above.

Official artifact · License

CreativeML OpenRAIL-M dated August 22, 2022. Conditional model and complementary-material copyright/patent grants. Attachment A use restrictions apply to use and outputs. Section 4 explicitly permits remote hosting but requires enforceable downstream use restrictions and notice, license copy, retained notices, and prominent modified-file notices. Require all users to comply with paragraph 5. No trademark grant, safety guarantee or blanket output-rights clearance. This bounded private research guide does not implement a third-party public hosting agreement.

  • 32 GiB RAM and 40 GiB disk are allocated host resources, not measured model requirements.
  • The four weight files total 5,481,058,519 bytes. Runtime copies, activations, safety checker and scheduler memory mean file size is not peak RAM or proof of fit.
  • No target install or inference, peak memory or performance was measured.

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.26 / hour
AWS public us-east-1 Linux On-Demand rate USD 0.2646 per billed instance-hour, no paid preinstalled software. Eight hours USD 2.1168; 24 hours USD 6.3504 compute. Idle running hours bill. Storage, egress, tax and administration separate; no Spot/reservation/discount assumed. Capacity/quota unverified. Region: us-east-1. SKU: r7i.xlarge Linux On-Demand. Tax: excluded. Price dated Oct 15, 2026. Price source
storage
$0.08 / GB month
US East (N. Virginia) gp3 USD 0.08 per GB-month; AWS defines GB as 1024^3 bytes. Selected 40 GiB root volume is USD 3.20 per full month, prorated by provisioned duration. Baseline 3000 IOPS / 125 MB/s; no extras assumed. Retained snapshots/resources separate; storage persists after instance 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. Install the explicitly pinned native CPU pipeline

    Install core package versions and their normal declared dependencies without stripping dependencies. Save the actual transitive resolution and run pip check. The native selected path uses CLIP text/image processing and PNDM; no training, export, all-extra or optional torchvision stack is selected. Package resolution and target compatibility are documented, not executed here.

    Command
    set -e
    sudo apt-get update
    sudo apt-get install -y python3.12 python3.12-venv curl ca-certificates openssl
    mkdir -p "$HOME/sd-v14-image/models"
    cd "$HOME/sd-v14-image"
    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'
    .venv/bin/python -m pip install 'diffusers==0.35.1' 'transformers==4.57.6' 'huggingface-hub==0.36.0' 'safetensors==0.6.2' 'accelerate==1.11.0' 'numpy==2.2.3' 'Pillow==11.1.0'
    .venv/bin/python -m pip check
    .venv/bin/python -m pip freeze > resolved-environment.txt
    .venv/bin/python - <<'PYVERS'
    import importlib.metadata as m
    for k,v in {'torch':'2.6.0+cpu','diffusers':'0.35.1','transformers':'4.57.6','huggingface-hub':'0.36.0','safetensors':'0.6.2','accelerate':'1.11.0','numpy':'2.2.3','Pillow':'11.1.0'}.items():
        assert m.version(k)==v,(k,m.version(k))
    try: m.version('torchvision')
    except m.PackageNotFoundError: pass
    else: raise RuntimeError('Use a fresh venv without optional torchvision')
    print('core versions verified; resolved transitive environment saved')
    PYVERS

    Expected result: Pinned core versions match, ordinary dependency resolution and pip check pass; resolved-environment.txt records the actual environment.

Download the model

  1. 1. Download and verify the complete selected native composition

    Four FP32 safetensors contain model weights. Eleven model, tokenizer, scheduler and image-processor text files complete the selected composition. The pinned snapshot metadata provides individual weight sizes and SHA digests; text digests are derived from archived raw bytes. Each stream must match size and digest before replacement. Retain the exact license. No pickle fallback or alternative checkpoint is selected.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    cat > assets.json <<'ASSETS'
    [
      {
        "path": "safety_checker/model.safetensors",
        "bytes": 1215981830,
        "sha256": "9d6a233ff6fd5ccb9f76fd99618d73369c52dd3d8222376384d0e601911089e8"
      },
      {
        "path": "text_encoder/model.safetensors",
        "bytes": 492265879,
        "sha256": "7b3a12df205cb3c74dd4eae4354d93f606ae6b3bc29d5d06fd97921cb9ad8a81"
      },
      {
        "path": "unet/diffusion_pytorch_model.safetensors",
        "bytes": 3438167534,
        "sha256": "145a07e0f05ec5bbe6e2e9faf608bdb311caf708895cac8c8ed713c59864e1e8"
      },
      {
        "path": "vae/diffusion_pytorch_model.safetensors",
        "bytes": 334643276,
        "sha256": "a2b5134f4dbc140d9c11f11cba3233099e00af40f262f136c691fb7d38d2194c"
      },
      {
        "path": "model_index.json",
        "bytes": 541,
        "sha256": "c7cc314014486aa2f7f17ab8f90197fe0412c818cdefb9e15601ae58752b5001"
      },
      {
        "path": "feature_extractor/preprocessor_config.json",
        "bytes": 342,
        "sha256": "2a1da83b5e1032aaeef397552ddb408dca0d8cd1dc58f61bf6abf38d6f33a0a2"
      },
      {
        "path": "safety_checker/config.json",
        "bytes": 4556,
        "sha256": "a069f3ab23e39f3d608b220d9ae6067a94e43405557e575cf7f98d7e8d2a255c"
      },
      {
        "path": "scheduler/scheduler_config.json",
        "bytes": 313,
        "sha256": "8335df29b53da12e9aeca35b1c2e60d88b23eae4cc5ad3d07efdcd7f003cc343"
      },
      {
        "path": "text_encoder/config.json",
        "bytes": 592,
        "sha256": "aa210e6d6abd239a466af57a1dadb62d5ced63295064d295a549e08a6c4a2020"
      },
      {
        "path": "tokenizer/merges.txt",
        "bytes": 524619,
        "sha256": "9fd691f7c8039210e0fced15865466c65820d09b63988b0174bfe25de299051a"
      },
      {
        "path": "tokenizer/special_tokens_map.json",
        "bytes": 472,
        "sha256": "c4864a9376a8401918425bed71fc14fc0e81f9b59ec45c1cf96cccb2df508eac"
      },
      {
        "path": "tokenizer/tokenizer_config.json",
        "bytes": 806,
        "sha256": "00439066fcba73de57644cf41e4e3b9f2dbb09d7f3fc2005898ba52399045882"
      },
      {
        "path": "tokenizer/vocab.json",
        "bytes": 1059962,
        "sha256": "e089ad92ba36837a0d31433e555c8f45fe601ab5c221d4f607ded32d9f7a4349"
      },
      {
        "path": "unet/config.json",
        "bytes": 743,
        "sha256": "d6749baad843798f21da6c2d3dd9d642e5ebb73455ade4763158f5c6d3e95b03"
      },
      {
        "path": "vae/config.json",
        "bytes": 551,
        "sha256": "0e5966d4d52c8077648754ffd2c14ab5e0b26a4bdfa6af1d207c27550fa6d2af"
      }
    ]
    ASSETS
    .venv/bin/python - <<'PYDL'
    import pathlib,json,urllib.request,hashlib,os
    root=pathlib.Path('models');root.mkdir(exist_ok=True)
    for row in json.loads(pathlib.Path('assets.json').read_text()):
        target=root/row['path'];target.parent.mkdir(parents=True,exist_ok=True)
        part=target.with_suffix(target.suffix+'.partial');h=hashlib.sha256();n=0
        url='https://huggingface.co/CompVis/stable-diffusion-v1-4/resolve/133a221b8aa7292a167afc5127cb63fb5005638b/'+row['path']
        with urllib.request.urlopen(url,timeout=60) as src,part.open('wb') as dst:
            for block in iter(lambda:src.read(1048576),b''):h.update(block);n+=len(block);dst.write(block)
        assert n==row['bytes'] and h.hexdigest()==row['sha256'],row['path']
        os.replace(part,target)
    print('15 exact pinned assets verified')
    PYDL
    curl --fail --location 'https://raw.githubusercontent.com/CompVis/stable-diffusion/21f890f9da3cfbeaba8e2ac3c425ee9e998d5229/LICENSE' -o MODEL-LICENSE.txt
    printf '%s  %s\n' 'be351ebe7ac01bcdbb018639aadcfd38f136b7dc3f2a3d4d3a24db51d1b210ef' MODEL-LICENSE.txt | sha256sum --check -

    Expected result: All 15 files and license pass byte/digest checks; failures terminate the block before starting the service.

Configure

  1. 1. Create the private native image harness

    The adapter loads all four native components using safetensors, CPU FP32, eval mode and four empty loading-diagnostic lists. It verifies every asset at each startup. CLIP tokenizes the original fixed prompt with BOS/EOS and without truncation; reject more than 77 positions before the pipeline can truncate. Native safety checker and feature processor remain loaded. The endpoint accepts only the cabin fixture; no arbitrary model, prompts, paths, uploads, URLs, tools or network actions are exposed. This wrapper is reader-authored and not an official CompVis server.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    cat > reader-image-server.py <<'PYSERVER'
    """Reader-authored bounded research endpoint, not an official or production server."""
    import base64, hashlib, hmac, io, json, os, pathlib, re, sys
    from http.server import BaseHTTPRequestHandler, HTTPServer
    PROMPT = 'A watercolor painting of a small red wooden cabin beside a blue lake, pine trees, daylight, no people, no text.'
    PARAMS = {'height':512,'width':512,'num_inference_steps':50,'guidance_scale':7.5,'num_images_per_prompt':1}
    
    def checked_info(value):
        if not isinstance(value,dict) or set(value)!={'missing_keys','unexpected_keys','mismatched_keys','error_msgs'} or any(not isinstance(v,list) or v for v in value.values()):
            raise ValueError('Checkpoint loading diagnostics are not four empty lists')
    
    def verify_assets(root):
        rows=json.loads(pathlib.Path('assets.json').read_text())
        if not isinstance(rows,list) or len(rows)!=15: raise ValueError('asset manifest shape')
        for row in rows:
            rel=row['path']
            if not isinstance(rel,str) or rel.startswith('/') or '..' in pathlib.PurePosixPath(rel).parts: raise ValueError('asset path')
            path=root/rel
            if path.is_symlink() or not path.is_file() or path.stat().st_size!=row['bytes']: raise ValueError('asset size')
            h=hashlib.sha256()
            with path.open('rb') as stream:
                for block in iter(lambda:stream.read(1048576),b''): h.update(block)
            if h.hexdigest()!=row['sha256']: raise ValueError('asset digest')
    
    def native_engine(root):
        os.environ.update(HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_HUB_DISABLE_TELEMETRY='1')
        verify_assets(root)
        import torch
        from transformers import CLIPTextModel, CLIPTokenizer, CLIPImageProcessor
        from diffusers import StableDiffusionPipeline, UNet2DConditionModel, AutoencoderKL, PNDMScheduler
        from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
        torch.set_num_threads(4); torch.set_num_interop_threads(1)
        common={'local_files_only':True,'use_safetensors':True,'torch_dtype':torch.float32,'output_loading_info':True}
        def load(cls,sub):
            model,info=cls.from_pretrained(str(root/sub),**common)
            checked_info(info)
            return model.to('cpu',dtype=torch.float32).eval()
        text=load(CLIPTextModel,'text_encoder'); unet=load(UNet2DConditionModel,'unet')
        vae=load(AutoencoderKL,'vae'); safety=load(StableDiffusionSafetyChecker,'safety_checker')
        tokenizer=CLIPTokenizer.from_pretrained(str(root/'tokenizer'),local_files_only=True)
        ids=tokenizer(PROMPT,add_special_tokens=True,truncation=False)['input_ids']
        if tokenizer.model_max_length!=77 or text.config.max_position_embeddings!=77 or not 2<=len(ids)<=77: raise ValueError('prompt exceeds exact conditioning window')
        processor=CLIPImageProcessor.from_pretrained(str(root/'feature_extractor'),local_files_only=True)
        scheduler=PNDMScheduler.from_pretrained(str(root/'scheduler'),local_files_only=True)
        pipe=StableDiffusionPipeline(vae=vae,text_encoder=text,tokenizer=tokenizer,unet=unet,scheduler=scheduler,safety_checker=safety,feature_extractor=processor,requires_safety_checker=True).to('cpu')
        pipe.set_progress_bar_config(disable=True)
        def run():
            with torch.inference_mode():
                out=pipe(PROMPT,negative_prompt='',generator=torch.Generator(device='cpu').manual_seed(12345),output_type='pil',**PARAMS)
            flags=out.nsfw_content_detected
            if not isinstance(flags,list) or len(flags)!=1 or type(flags[0]) is not bool: raise ValueError('missing checker result')
            if flags[0]: return {'blocked':True}
            if len(out.images)!=1 or out.images[0].size!=(512,512) or out.images[0].mode!='RGB': raise ValueError('native image shape')
            buf=io.BytesIO();out.images[0].save(buf,format='PNG');raw=buf.getvalue()
            if not 8<len(raw)<=2097152 or not raw.startswith(b'\x89PNG\r\n\x1a\n'): raise ValueError('PNG boundary')
            return {'blocked':False,'png_base64':base64.b64encode(raw).decode('ascii'),'sha256':hashlib.sha256(raw).hexdigest(),'width':512,'height':512,'prompt_tokens':len(ids),'seed':12345,'requested_steps':50,'output_text_tokens':None}
        return run,len(ids)
    
    def server(engine,token,prompt_tokens,port=8997):
        if not re.fullmatch(r'[0-9a-f]{64}',token): raise ValueError('invalid private key')
        class Handler(BaseHTTPRequestHandler):
            protocol_version='HTTP/1.0'
            def log_message(self,*args): pass
            def setup(self): super().setup();self.connection.settimeout(15)
            def send(self,status,value):
                data=json.dumps(value,allow_nan=False,separators=(',',':')).encode()
                self.send_response(status);self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(data)));self.send_header('Connection','close');self.end_headers();self.wfile.write(data);self.close_connection=True
            def auth(self):
                values=self.headers.get_all('Authorization',[])
                return len(values)==1 and hmac.compare_digest(values[0].encode('utf-8'), ('Bearer '+token).encode('ascii'))
            def do_GET(self):
                if not self.auth(): return self.send(401,{'error':'unauthorized'})
                if self.path!='/health': return self.send(404,{'error':'not_found'})
                return self.send(200,{'ready':True,'context_positions':77,'prompt_tokens':prompt_tokens,'output':'PNG','parameters':PARAMS})
            def do_POST(self):
                if not self.auth(): return self.send(401,{'error':'unauthorized'})
                if self.path!='/v1/image': return self.send(404,{'error':'not_found'})
                lens=self.headers.get_all('Content-Length',[])
                if self.headers.get_all('Transfer-Encoding',[]): return self.send(400,{'error':'framing'})
                if len(lens)!=1 or not re.fullmatch('[0-9]{1,4}',lens[0]): return self.send(411,{'error':'length_required'})
                n=int(lens[0])
                if not 1<=n<=128:return self.send(413,{'error':'body_bound'})
                if self.headers.get_content_type()!='application/json':return self.send(415,{'error':'json_required'})
                try:
                    raw=self.rfile.read(n)
                    if len(raw)!=n: raise ValueError('short body')
                    def unique(pairs):
                        d={}
                        for k,v in pairs:
                            if k in d:raise ValueError('duplicate key')
                            d[k]=v
                        return d
                    value=json.loads(raw,object_pairs_hook=unique,parse_constant=lambda _:(_ for _ in ()).throw(ValueError('constant')))
                    if value!={'fixture':'cabin'}: raise ValueError('fixed fixture only')
                except (ValueError,UnicodeError):return self.send(400,{'error':'invalid_request'})
                try:
                    result=engine()
                    if result=={'blocked':True}:return self.send(422,{'error':'native_checker_flagged','image_returned':False})
                    if not isinstance(result,dict) or result.get('blocked') is not False:raise ValueError('invalid engine result')
                    return self.send(200,result)
                except Exception:return self.send(500,{'error':'native_inference_failed'})
        return HTTPServer(('127.0.0.1',port),Handler)
    
    if __name__=='__main__':
        key=pathlib.Path('server.key').read_text().strip();engine,count=native_engine(pathlib.Path('models').resolve())
        server(engine,key,count).serve_forever()
    PYSERVER

    Expected result: Local adapter source is saved exactly. Review it before use; no model load occurs in this configure step.

Start the model

  1. 1. Start on authenticated loopback

    Keep the existing nonempty secret stable; an empty existing file is an error, not a silent rotation. Startup performs all asset and native load checks before binding. Inspect server.log if startup exits. Native CPU execution may take substantial time; no latency or cancellation guarantee is claimed.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    if [ -e server.pid ]; then echo 'Existing PID record: inspect and stop that process first'; exit 1; fi
    umask 077
    if [ ! -e server.key ]; then openssl rand -hex 32 > server.key; fi
    test -s server.key
    export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_HUB_DISABLE_TELEMETRY=1
    export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4
    nohup .venv/bin/python reader-image-server.py > server.log 2>&1 &
    printf '%s\n' "$!" > server.pid
    printf 'Started PID %s; inspect server.log and authenticated health after model loading\n' "$(cat server.pid)"

    Expected result: A PID record and log appear; health becomes ready only after native loading and prompt validation.

Connect to your endpoint

http://127.0.0.1:8997/v1/image

Only the host loopback interface; single serial request. Health is /health on the same loopback port.

Access: loopback. Bearer token read from server.key; do not print or share it. POST JSON contains fixture with value cabin. Response contains PNG base64, digest, dimensions, actual prompt count, seed and requested scheduler steps. The native checker flag returns 422 without an image. Duplicate keys, oversized bodies and unsupported framing are rejected. No TLS or production inference deadline is provided.

Verify the setup

  1. 1. Open the private SSH path

    From your local computer use the existing SSH identity and actual host. Keep remote 8997 on loopback. The remaining verification commands run inside SSH on the instance and use its key directly; this tunnel is optional for your separately secured local client.

    Command
    ssh -N -L 8997:127.0.0.1:8997 ubuntu@YOUR_EXISTING_INSTANCE_HOST

    Expected result: The local 8997 tunnel reaches only the remote loopback service; this command does not open an inbound model port.

  2. 2. Check authenticated native readiness

    Run after startup has completed; do not treat an open socket as successful native loading. Health exposes actual prompt count, fixed image parameters and the 77-position conditioning window.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    .venv/bin/python - <<'PYHEALTH'
    import pathlib,urllib.request,json
    key=pathlib.Path('server.key').read_text().strip()
    r=urllib.request.Request('http://127.0.0.1:8997/health',headers={'Authorization':'Bearer '+key})
    with urllib.request.urlopen(r,timeout=60) as response:d=json.load(response)
    assert d['ready'] is True and d['context_positions']==77 and 2<=d['prompt_tokens']<=77
    print(d)
    PYHEALTH

    Expected result: Ready true, actual prompt positions within 77 and the documented fixed image parameters.

  3. 3. Generate and inspect one original synthetic image

    The prompt asks for a watercolor red wooden cabin beside a blue lake, pine trees and daylight, with no people or text. Generation is 512 by512, one image, seed 12345, requested 50 PNDM steps and guidance 7.5. Verify returned PNG digest/shape, then inspect cabin.png visually for those features. Exact pixels, scene correctness and cross-platform reproducibility are not guaranteed. A 422 native checker flag is an observable blocked result; never disable the checker or present a blank image as success. Client timeout does not cancel native inference.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    .venv/bin/python - <<'PYIMAGE'
    import pathlib,urllib.request,json,base64,hashlib,io
    from PIL import Image
    key=pathlib.Path('server.key').read_text().strip()
    r=urllib.request.Request('http://127.0.0.1:8997/v1/image',data=b'{"fixture":"cabin"}',headers={'Authorization':'Bearer '+key,'Content-Type':'application/json'})
    with urllib.request.urlopen(r,timeout=3600) as response:d=json.load(response)
    assert d['blocked'] is False and d['width']==d['height']==512 and d['requested_steps']==50
    assert d['seed']==12345 and 2<=d['prompt_tokens']<=77 and d['output_text_tokens'] is None
    raw=base64.b64decode(d['png_base64'],validate=True)
    assert 8<len(raw)<=2097152 and hashlib.sha256(raw).hexdigest()==d['sha256']
    image=Image.open(io.BytesIO(raw));image.load();assert image.format=='PNG' and image.size==(512,512) and image.mode=='RGB'
    pathlib.Path('cabin.png').write_bytes(raw);print('Verified image bytes; visually inspect cabin.png for the stated cabin/lake/pines prompt.')
    PYIMAGE

    Expected result: Either one verified PNG for manual scene inspection, or a visible checker/native failure requiring investigation. No exact generated image or measured quality is asserted.

  4. 4. Check authentication and fixed request boundary

    These negative checks must fail before inference; they do not generate additional images.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    .venv/bin/python - <<'PYERROR'
    import pathlib,urllib.request,urllib.error,json
    url='http://127.0.0.1:8997';key=pathlib.Path('server.key').read_text().strip()
    for path,body,auth,expected in [('/health',None,False,401),('/v1/image',b'{"fixture":"other"}',True,400)]:
        headers={'Content-Type':'application/json'}
        if auth:headers['Authorization']='Bearer '+key
        try:urllib.request.urlopen(urllib.request.Request(url+path,data=body,headers=headers),timeout=30)
        except urllib.error.HTTPError as e:assert e.code==expected;print(e.code,json.load(e))
        else:raise RuntimeError('Expected error did not occur')
    PYERROR

    Expected result: Unauthenticated health returns 401 and unknown fixture returns 400.

Performance evidence

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

Limits and troubleshooting

  • The77-position limit is CLIP text conditioning including special tokens. Output is an image; pixels,64 by64 latent positions, scheduler evaluations and50 requested steps are not generated text tokens.
  • A fixed seed is a reproducibility aid within an environment, not a cross-version/platform byte guarantee. Native scheduler internals may perform a different number of UNet evaluations than the requested step count.
  • The native safety checker is retained but can miss harmful content or flag benign images. Neither the checker nor this guide guarantees safety, rights clearance or accuracy. Read the publisher model card and full use restrictions.
  • This is one source-qualified v1-4 text-to-image CPU job, not complete v1 family coverage. Other original checkpoints, image-to-image, GPU routes and public-service operational/legal work remain open.
  • No target install, model load, generation, peak memory, fit, throughput, price outcome or visual quality was measured. Four CPU threads are requested through Torch and environment variables; other libraries may have their own behavior.
  • Inference is serial and blocks this simple HTTPServer, including health while busy. Socket/client timeouts do not enforce an inference deadline; stop the process to terminate an unwanted long computation.
Asset checksum, strict loading diagnostics or offline load fails
Stop and inspect the exact asset/path/version. All four diagnostic lists must be empty. Do not ignore missing/mismatched tensors, allow random initialization, use pickle fallback, fetch a mutable checkpoint or turn off offline loading.
Request errors, checker flag or missing scene elements
Confirm the fixed fixture and private key. A native checker flag is a failed/blocked output, not permission to bypass filtering. Visually missing cabin/lake/pines is an unverified semantic result; retain it honestly and investigate without asserting model correctness.
Slow CPU generation, memory exhaustion or health unavailable while busy
This is an unmeasured32 GiB planning allocation. Stop the process if necessary; do not assume aggregate disk/weight size proves memory fit. Serial inference blocks health. Investigate host/process usage before selecting a different qualified configuration.

Stop the model

  1. 1. Stop and verify the recorded service

    Verify PID command identity before sending termination. Preserve logs and generated image if needed. Stopping this Python process does not stop AWS compute or storage billing.

    Command
    set -e
    cd "$HOME/sd-v14-image"
    if [ -e server.pid ]; then
      pid=$(cat server.pid)
      case "$pid" in ''|*[!0-9]*) echo 'Invalid PID record'; exit 1;; esac
      if kill -0 "$pid" 2>/dev/null; then
        ps -p "$pid" -o args= | grep -F 'reader-image-server.py' >/dev/null || { echo 'PID identity mismatch; inspect manually'; exit 1; }
        kill "$pid"
        for n in 1 2 3 4 5; do kill -0 "$pid" 2>/dev/null || break; sleep 1; done
        if kill -0 "$pid" 2>/dev/null; then echo 'Still running; inspect before further action'; exit 1; fi
      fi
      rm server.pid
    fi

    Expected result: Recorded service exits and PID record is removed; if identity differs or remains running, stop and inspect manually.

Uninstall

  1. 1. Remove only this dedicated environment

    Stop first and preserve any image/logs you want. The command only removes this dedicated directory; do not reuse it for unrelated data. Model license notices must accompany any separately retained distributed model copies.

    Command
    set -e
    cd "$HOME"
    test ! -e "$HOME/sd-v14-image/server.pid"
    rm -r -- "$HOME/sd-v14-image"

    Expected result: The dedicated model files, venv, key, logs and optional generated image 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 service stops.

Sources and verification

Sources checked Oct 16, 2026. Verification source

Compare this configuration

Benchmarks

Performance scores for Stable Diffusion across standard benchmarks.

CVPR 2022 latent diffusion paperhttps://openaccess.thecvf.com/content/CVPR2022/html/Rombach_High-Resolution_Image_Synthesis_With_Latent_Diffusion_Models_CVPR_2022_paper.html · Jun 2022
--

Pricing and access

Open research weights/source; no official hosted API price in the CompVis repository. Runtime cost depends on GPU hardware or a third-party image generation provider.

CompVis logo
CompVisopen source

Computer vision and generative AI research from LMU Munich

Founded 2017Munich, Germany
View full profile