Views
No views yet
| Used Model | License |
|---|---|
| Llama-3.1-Swallow-8B-Instruct-v0.5 | Llama 3.1 and Gemma |
| Llama-3.1-8B-Instruct | Llama 3.1 |
0.10.01base_model: tokyotech-llm/Llama-3.1-Swallow-8B-Instruct-v0.5
2# optionally might have model_type or tokenizer_type
3model_type: AutoModelForCausalLM
4tokenizer_type: AutoTokenizer
5# Automatically upload checkpoint and final model to HF
6# hub_model_id: username/custom_model_name
7
8load_in_8bit: false
9load_in_4bit: true
10
11datasets:
12 - path: merged_medical_qa_MIT.json
13 type: alpaca
14dataset_prepared_path:
15val_set_size: 0
16output_dir: ./outputs/qlora-out_swallow-8b
17
18adapter: qlora
19lora_model_dir:
20
21sequence_len: 2048
22sample_packing: true
23pad_to_sequence_len: true
24
25lora_r: 32
26lora_alpha: 16
27lora_dropout: 0.05
28lora_target_linear: true
29
30wandb_project:
31wandb_entity:
32wandb_watch:
33wandb_name:
34wandb_log_model:
35
36gradient_accumulation_steps: 4
37micro_batch_size: 2
38num_epochs: 1
39optimizer: paged_adamw_32bit
40lr_scheduler: cosine
41learning_rate: 0.0002
42
43bf16: auto
44tf32: false
45
46gradient_checkpointing: true
47resume_from_checkpoint:
48logging_steps: 1
49flash_attention: true
50
51warmup_steps: 10
52evals_per_epoch: 4
53saves_per_epoch: 1
54weight_decay: 0.0
55special_tokens:
56 pad_token: "<|end_of_text|>"
571conda create --name medexamdoc python=3.11
2conda activate medexamdoc
3pip install PEFT==0.15.2 Transformers==4.52.3 torch==2.5.1 Datasets==3.6.0 Tokenizers==0.21.2
4hf download IngentaAITeam/MedExamDoc-Llama-3.1-Swallow-8B-Instruct-v0.51from transformers import AutoTokenizer, AutoModelForCausalLM
2from peft import PeftModel
3import torch
4import re
5import time
6
7# 基本モデル読み込み
8model_path = "IngentaAITeam/MedExamDoc-Llama-3.1-Swallow-8B-Instruct-v0.5"
9
10def load_model(model_name, device="cuda"):
11 """モデルを読み込み"""
12 print(f"モデルを読み込み中:{model_name}")
13 tokenizer = AutoTokenizer.from_pretrained(model_name)
14 model = AutoModelForCausalLM.from_pretrained(
15 model_name,
16 torch_dtype=torch.float16 if device == "cuda" else torch.float32,
17 device_map="auto" if device == "cuda" else None
18 )
19 model.eval()
20 return tokenizer, model
21
22def create_medical_prompt_template():
23 """医学問題のプロンプトテンプレートを作成"""
24 template = """Answer this medical multiple choice question by selecting the correct option letter (A, B, C, D, or E).
25
26Question: {question}
27
28Options:
29{options}
30Answer:"""
31 return template
32
33def format_question(question_data):
34 """問題をフォーマット"""
35 question = question_data['question']
36 options = question_data['options']
37
38 # 選択肢をフォーマット(訓練データ形式と完全一致)
39 options_text = ""
40 for key, value in options.items():
41 options_text += f"{key}. {value}\n"
42
43 template = create_medical_prompt_template()
44 prompt = template.format(
45 question=question,
46 options=options_text.rstrip() # 最後の改行を削除
47 )
48
49 return prompt
50
51def extract_answer(response):
52 """モデルの回答から選択肢の文字を抽出"""
53 pattern = r'\b[A-E]\b'
54 matches = re.findall(pattern, response.upper())
55 return matches[0] if matches else None
56
57def extract_multiple_answers(response):
58 """複数選択肢の回答を抽出し、重複を除去"""
59 pattern = r'\b[A-E]\b'
60 matches = re.findall(pattern, response.upper())
61 # 重複を除去し、ソート
62 unique_matches = list(dict.fromkeys(matches)) # 順序を保持して重複除去
63 return ''.join(sorted(unique_matches)) if unique_matches else None
64
65def generate_answer(tokenizer, model, prompt, device="cuda"):
66 """回答を生成"""
67 inputs = tokenizer(prompt, return_tensors="pt").to(device)
68
69 # 推論時間を測定
70 start_time = time.time()
71 with torch.no_grad():
72 outputs = model.generate(
73 **inputs,
74 max_new_tokens=64,
75 temperature=0.0,
76 do_sample=False,
77 pad_token_id=tokenizer.eos_token_id
78 )
79 end_time = time.time()
80
81 response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
82 inference_time = end_time - start_time
83
84 return response.strip(), inference_time
85
86# 使用例
87tokenizer, model = load_model(model_path)
88
89# 医学問題の例
90question_data = {
91 'question': 'What is the most common cause of acute myocardial infarction?',
92 'options': {
93 'A': 'Coronary artery spasm',
94 'B': 'Atherosclerotic plaque rupture',
95 'C': 'Coronary artery embolism',
96 'D': 'Coronary artery dissection',
97 'E': 'Takotsubo cardiomyopathy'
98 }
99}
100
101# プロンプトをフォーマット
102prompt = format_question(question_data)
103print("プロンプト:")
104print(prompt)
105print("---" * 40)
106
107# 回答を生成
108response, inference_time = generate_answer(tokenizer, model, prompt)
109predicted_answer = extract_answer(response)
110
111print("モデル回答:")
112print(response)
113print(f"抽出された選択肢: {predicted_answer}")
114print(f"推論時間: {inference_time:.3f}秒")
115| Dataset | # of Training Samples | Data Source | License | Data Selection Method | Version(Commit ID) |
|---|---|---|---|---|---|
| JMedBench | 218,912 | - medmcqa_jp (translated from MedMCQA) - usmleqa_jp (translated from MedQA) - medqa_jp (translated from MedQA) - mmlu_medical_jp (translated from MMLU) - pubmedqa_jp (translated from PubMedQA) | MIT | MultipleChoiceQA | fe772d4fb76c11a4b24e06a2d06c72a7e3e32ef5 |
| KokushiMD-10 | 1,386 | Japanese national healthcare licensing examinations (2020–2024) | MIT | text_only=True & profession=pharmacy (some questions in profession medicine overlapping with IgakuQA test set, so profession medicine are excluded) | c381c014c6769d0a8ca40356d7c30a969a12816d |
| Dataset | # of Testing Samples | Data Source | License | Data Selection Method | Version(Commit ID) |
|---|---|---|---|---|---|
| IgakuQA | 2,000 | Japanese medical licensing examinations (2018–2022) | Public(Ministry of Health, Labour and Welfare) | All data | 2bc4c3d159cf5505f6253d24a909fbd53237e239 |
1"""Answer this medical multiple choice question by selecting the correct option letter (A, B, C, D, or E).
2
3Question: {question}
4
5Options:
6{options}
7Answer:"""| Model Configuration | Overall Accuracy | Single-choice accuracy | Multiple-choice accuracy | Notes |
|---|---|---|---|---|
| Llama-3.1-Swallow-8B-Instruct-v0.5 | 55.75% | 60.33% | 30.87% | Base model |
| MedExamDoc-Llama-3.1-Swallow-8B-Instruct-v0.5 | 62.40% | 66.31% | 41.16% | Our fine-tuned model |
| JPharmatron-7B | 61.25% | 67.02% | 29.90% | We use the open source model with our script to test accuracy |
| JPharmatron-7B + finetune | 65.90% | 71.11% | 37.62% | We finetune the model, and use our script to test accuracy. After finetune, the accuracy improve by 4.65%. |
| student_majority | 93.90% | 94.24% | 91.95% | Provided by IgakuQA; selects the option most frequently chosen by students |
| GPT-4 | 76.60% | 77.97% | 68.79% | Provided by IgakuQA benchmark |
| translate_chatgpt | 56.60% | 60.11% | 36.58% | Provided by IgakuQA benchmark; approximately ChatGPT (2023) with translation |
| ChatGPT | 53.95% | 56.99% | 36.58% | Provided by IgakuQA benchmark; approximately ChatGPT (2023) |
| GPT-3 | 40.35% | 43.13% | 24.50% | Provided by IgakuQA benchmark |