File size: 3,139 Bytes
f32c317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
"""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()