Run this model with HF Jobs

Run 2npc/gemma2-9b-drs-lora on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/2npc/gemma2-9b-drs-lora. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/2npc/gemma2-9b-drs-lora on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
gemma2-9b-drs-lora / inference.py
2npc's picture
Upload gemma-2-9b-it DRS parsing LoRA adapter (silver_gold)
c8b5cbe verified
Raw History Blame Contribute Delete
3.57 kB
"""Run the silver_gold DRS-parsing LoRA adapter on top of google/gemma-2-9b-it.
Examples
--------
# one sentence
python inference.py --text "He organized a summer rock festival."
# a JSON file: a list of {"input": ...} records (an "instruction" field is
# optional); the prediction is written to each record's "output" field
python inference.py --in_json data.json --out_json data_pred.json
"""
import argparse
import json
import os
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
HERE = os.path.dirname(os.path.abspath(__file__))
# The instruction used for every training example.
INSTRUCTION = "Please parse the following text in Discourse Representation Structure:"
def build_prompt(instruction: str, inp: str) -> str:
# Same layout as the LLaMA-Factory "gemma" template used in training.
# The tokenizer adds <bos> itself.
content = ((instruction or "").strip() + "\n" + (inp or "").strip()).strip()
return f"<start_of_turn>user\n{content}<end_of_turn>\n<start_of_turn>model\n"
def load(base: str, adapter: str):
use_cuda = torch.cuda.is_available()
dtype = torch.bfloat16 if use_cuda else torch.float32
tok = AutoTokenizer.from_pretrained(base)
model = AutoModelForCausalLM.from_pretrained(
base, torch_dtype=dtype, device_map="auto" if use_cuda else None
)
model = PeftModel.from_pretrained(model, adapter).eval()
if not use_cuda:
print("Warning: no GPU found, running on CPU (very slow).")
return tok, model
@torch.no_grad()
def generate(tok, model, prompt: str, max_new_tokens: int) -> str:
inputs = tok(prompt, return_tensors="pt").to(model.device)
out = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=False, # greedy, deterministic
pad_token_id=tok.pad_token_id,
eos_token_id=[tok.eos_token_id, tok.convert_tokens_to_ids("<end_of_turn>")],
)
new_tokens = out[0][inputs["input_ids"].shape[1]:]
return tok.decode(new_tokens, skip_special_tokens=True).strip()
def main() -> None:
p = argparse.ArgumentParser()
p.add_argument("--base", default="google/gemma-2-9b-it")
p.add_argument("--adapter", default=HERE, help="folder with adapter_model.safetensors")
p.add_argument("--instruction", default=INSTRUCTION,
help="instruction text; defaults to the one used in training")
p.add_argument("--text", help="input text (single-input mode)")
p.add_argument("--in_json", help="JSON list of {instruction, input} records")
p.add_argument("--out_json", help="where to write predictions")
p.add_argument("--max_new_tokens", type=int, default=1024)
a = p.parse_args()
if not a.text and not a.in_json:
p.error("give --text or --in_json")
tok, model = load(a.base, a.adapter)
if a.text:
print(generate(tok, model, build_prompt(a.instruction, a.text), a.max_new_tokens))
return
with open(a.in_json, encoding="utf-8") as f:
data = json.load(f)
for i, ex in enumerate(data, 1):
prompt = build_prompt(ex.get("instruction") or a.instruction, ex.get("input", ""))
ex["output"] = generate(tok, model, prompt, a.max_new_tokens)
if i % 10 == 0 or i == len(data):
print(f"{i}/{len(data)} done")
out = a.out_json or a.in_json.replace(".json", "_pred.json")
with open(out, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
print("Wrote", out)
if __name__ == "__main__":
main()