"""Minimal synthetic inference example for the TRoB-1 PEFT adapter.""" from __future__ import annotations import json import os import torch from peft import PeftModel from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig BASE_MODEL_ID = "google/gemma-2-9b-it" ADAPTER_MODEL_ID = os.environ.get( "TROB1_ADAPTER_ID", "lyt9906/TRoB-1", ) STEP1_SYSTEM = """You are an expert systematic reviewer using the Cochrane Risk of Bias tool (RoB 1.0). Assess only the requested RoB 1 domain using the supplied original excerpt. The original excerpt is the source of truth. Do not invent facts or switch domains. The supporting_quote must be copied exactly from the original excerpt and should be the shortest relevant continuous span. Return exactly one valid JSON object with the keys bias_domain, judgement, supporting_quote, and confidence. Allowed judgements are Low risk, High risk, and Unclear risk. Allowed confidence values are High, Medium, and Low. Do not include an explanation in Step 1.""" def load_model(): quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.float16, ) tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID) if tokenizer.pad_token_id is None and tokenizer.eos_token_id is not None: tokenizer.pad_token = tokenizer.eos_token base_model = AutoModelForCausalLM.from_pretrained( BASE_MODEL_ID, quantization_config=quantization_config, device_map="auto", ) model = PeftModel.from_pretrained(base_model, ADAPTER_MODEL_ID) model.eval() return tokenizer, model def main(): tokenizer, model = load_model() synthetic_excerpt = ( "Participants were randomly assigned using a computer-generated " "random number sequence." ) user_prompt = f"""RoB 1 domain: Random sequence generation Original excerpt: {synthetic_excerpt} Return exactly one JSON object with the keys: - bias_domain - judgement - supporting_quote - confidence """ messages = [ {"role": "system", "content": STEP1_SYSTEM}, {"role": "user", "content": user_prompt}, ] input_ids = tokenizer.apply_chat_template( messages, add_generation_prompt=True, return_tensors="pt", ).to(model.device) with torch.inference_mode(): output_ids = model.generate( input_ids=input_ids, do_sample=False, max_new_tokens=1024, repetition_penalty=1.0, pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id, eos_token_id=tokenizer.eos_token_id, ) generated = tokenizer.decode( output_ids[0][input_ids.shape[-1] :], skip_special_tokens=True, ).strip() print(generated) try: print(json.dumps(json.loads(generated), indent=2, ensure_ascii=False)) except json.JSONDecodeError: print("The generated text was not valid JSON. Apply the predefined retry workflow.") if __name__ == "__main__": main()