Upload folder using huggingface_hub
Browse filesFiles changed (8)
- DockerfileAdded+42
- README.md+4-6
- adapter_config.jsonAdded+41
- adapter_model.safetensorsAdded+3
- merge_and_save.pyAdded+38
- server.pyAdded+123
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+12
123456789101112131415161718192021222324252627282930313233343536373839404142# Stage 1: Merge LoRA adapter into base model (CPU only)FROM python:3.11-slim AS merger
RUN pip install --no-cache-dir \ torch==2.5.1 --index-url https://download.pytorch.org/whl/cpu \ && pip install --no-cache-dir \ transformers==4.51.3 \ peft==0.18.1 \ safetensors \ accelerate
COPY adapter_config.json /adapter/COPY adapter_model.safetensors /adapter/COPY tokenizer.json /adapter/COPY tokenizer_config.json /adapter/
COPY merge_and_save.py /merge_and_save.py
RUN python /merge_and_save.py
# Stage 2: Lightweight runtime (CPU — free tier on HF Spaces)FROM python:3.11-slim AS runtime
RUN pip install --no-cache-dir \ torch==2.5.1 --index-url https://download.pytorch.org/whl/cpu \ && pip install --no-cache-dir \ transformers==4.51.3 \ safetensors \ accelerate \ fastapi==0.115.12 \ uvicorn[standard]==0.34.2
RUN useradd -m -u 1000 appuser
COPY --from=merger --chown=1000:1000 /merged_model /modelCOPY --chown=1000:1000 server.py /app/server.py
USER appuserENV MODEL_DIR=/modelEXPOSE 7860
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "7860", "--app-dir", "/app"]12345678910---title: Seng Apiemoji: 🐨colorFrom: bluecolorTo: greensdk: dockerpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678---title: SENG APIemoji: "\U0001F9E0"colorFrom: bluecolorTo: purplesdk: dockerapp_port: 7860---
1234567891011121314151617181920212223242526272829303132333435363738394041{ "alora_invocation_tokens": null, "alpha_pattern": {}, "arrow_config": null, "auto_mapping": null, "base_model_name_or_path": "gpt2-large", "bias": "none", "corda_config": null, "ensure_weight_tying": false, "eva_config": null, "exclude_modules": null, "fan_in_fan_out": true, "inference_mode": true, "init_lora_weights": true, "layer_replication": null, "layers_pattern": null, "layers_to_transform": null, "loftq_config": {}, "lora_alpha": 32, "lora_bias": false, "lora_dropout": 0.05, "megatron_config": null, "megatron_core": "megatron.core", "modules_to_save": null, "peft_type": "LORA", "peft_version": "0.18.1", "qalora_group_size": 16, "r": 16, "rank_pattern": {}, "revision": null, "target_modules": [ "c_proj", "c_attn" ], "target_parameters": null, "task_type": "CAUSAL_LM", "trainable_token_indices": null, "use_dora": false, "use_qalora": false, "use_rslora": false}123version https://git-lfs.github.com/spec/v1oid sha256:3be1c1ea2eba9b7ba1303c969b4ba41dcc6cb1fc2bb1aeec66653167d904745asize 324683681234567891011121314151617181920212223242526272829303132333435363738"""Merge LoRA adapter into gpt2-large base model and save.
Runs at Docker build time (CPU only). The merged model eliminates thePEFT dependency at runtime, simplifying the serving image."""
import torchfrom peft import PeftModelfrom transformers import AutoModelForCausalLM, AutoTokenizer
ADAPTER_DIR = "/adapter"OUTPUT_DIR = "/merged_model"BASE_MODEL = "gpt2-large"
def main(): print(f"Loading base model: {BASE_MODEL}") base_model = AutoModelForCausalLM.from_pretrained( BASE_MODEL, torch_dtype=torch.float32 )
print(f"Loading LoRA adapter from: {ADAPTER_DIR}") model = PeftModel.from_pretrained(base_model, ADAPTER_DIR)
print("Merging adapter into base model...") model = model.merge_and_unload()
print(f"Saving merged model to: {OUTPUT_DIR}") model.save_pretrained(OUTPUT_DIR)
tokenizer = AutoTokenizer.from_pretrained(ADAPTER_DIR) tokenizer.save_pretrained(OUTPUT_DIR)
print("Merge complete.")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""FastAPI server for SENG inference.
Loads the merged GPT-2 Large model (LoRA already folded in) and exposesendpoints that replicate the exact inference logic from run_pipeline.py."""
import os
import torchfrom fastapi import FastAPIfrom pydantic import BaseModelfrom transformers import AutoModelForCausalLM, AutoTokenizer
MODEL_DIR = os.environ.get("MODEL_DIR", "/model")INSTRUCTION = "Analyze these repository events and extract development beliefs."CHUNK_SIZE = 12
app = FastAPI(title="SENG API")
# Globals populated at startupmodel = Nonetokenizer = Nonedevice = None
class PredictRequest(BaseModel): text: str
class BatchRequest(BaseModel): narrative: str
@app.on_event("startup")def load_model(): global model, tokenizer, device
device = "cuda" if torch.cuda.is_available() else "cpu" dtype = torch.float16 if device == "cuda" else torch.float32
print(f"Loading model from {MODEL_DIR} on {device} ({dtype})") tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR) model = AutoModelForCausalLM.from_pretrained( MODEL_DIR, torch_dtype=dtype ).to(device) model.eval() print("Model loaded.")
@app.get("/health")def health(): return { "status": "healthy" if model is not None else "loading", "model_loaded": model is not None, "gpu_available": torch.cuda.is_available(), }
def run_inference(text: str) -> str: """Run inference on a single text chunk.
Replicates run_pipeline.py:120-146 exactly. """ prompt = ( f"### Instruction:\n{INSTRUCTION}\n\n" f"### Input:\n{text}\n\n" f"### Response:\n" )
inputs = tokenizer( prompt, return_tensors="pt", truncation=True, max_length=768, ).to(device)
with torch.no_grad(): outputs = model.generate( **inputs, max_new_tokens=512, temperature=0.7, do_sample=True, top_p=0.9, pad_token_id=tokenizer.eos_token_id, repetition_penalty=1.2, )
generated = tokenizer.decode( outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True, ).strip()
return generated
def chunk_narrative(narrative: str, chunk_size: int = CHUNK_SIZE) -> list[str]: """Split narrative into non-overlapping chunks.
Replicates run_pipeline.py:89-99. """ lines = [line.rstrip("\n") for line in narrative.splitlines() if line.strip()] chunks = [] for i in range(0, len(lines), chunk_size): chunk_lines = lines[i : i + chunk_size] if chunk_lines: chunks.append("\n".join(chunk_lines)) return chunks
@app.post("/predict")def predict(req: PredictRequest): generated = run_inference(req.text) return {"generated_text": generated}
@app.post("/batch")def batch(req: BatchRequest): chunks = chunk_narrative(req.narrative) results = [] for i, chunk in enumerate(chunks): generated = run_inference(chunk) results.append({"chunk_index": i, "generated_text": generated}) return {"total_chunks": len(chunks), "results": results}123456789101112{ "add_prefix_space": false, "backend": "tokenizers", "bos_token": "<|endoftext|>", "eos_token": "<|endoftext|>", "errors": "replace", "is_local": false, "model_max_length": 1024, "pad_token": "<|endoftext|>", "tokenizer_class": "GPT2Tokenizer", "unk_token": "<|endoftext|>"}DockerfileAdded+42
README.md+4-6
adapter_config.jsonAdded+41
adapter_model.safetensorsAdded+3
merge_and_save.pyAdded+38
server.pyAdded+123
tokenizer.jsonAdded
tokenizer_config.jsonAdded+12