Views
No views yet
1import numpy as np
2import torch
3from transformers import AutoTokenizer, AutoModelForCausalLM
4import simple_slice_viewer as ssv
5import SimpleITK as sikt
6
7device = torch.device('cuda') # 'cpu', 'cuda'
8dtype = torch.bfloat16 # or bfloat16, float16, float32
9
10model_name_or_path = 'GoodBaiBai88/M3D-LaMed-Llama-2-7B'
11proj_out_num = 256
12
13# Prepare your 3D medical image:
14# 1. The image shape needs to be processed as 1*32*256*256, consider resize and other methods.
15# 2. The image needs to be normalized to 0-1, consider Min-Max Normalization.
16# 3. The image format needs to be converted to .npy
17# 4. Although we did not train on 2D images, in theory, the 2D image can be interpolated to the shape of 1*32*256*256 for input.
18image_path = "./Data/data/examples/example_01.npy"
19
20model = AutoModelForCausalLM.from_pretrained(
21 model_name_or_path,
22 torch_dtype=dtype,
23 device_map='auto',
24 trust_remote_code=True)
25tokenizer = AutoTokenizer.from_pretrained(
26 model_name_or_path,
27 model_max_length=512,
28 padding_side="right",
29 use_fast=False,
30 trust_remote_code=True
31)
32
33model = model.to(device=device)
34
35# question = "Can you provide a caption consists of findings for this medical image?"
36question = "What is liver in this image? Please output the segmentation mask."
37# question = "What is liver in this image? Please output the box."
38
39image_tokens = "<im_patch>" * proj_out_num
40input_txt = image_tokens + question
41input_id = tokenizer(input_txt, return_tensors="pt")['input_ids'].to(device=device)
42
43image_np = np.load(image_path)
44image_pt = torch.from_numpy(image_np).unsqueeze(0).to(dtype=dtype, device=device)
45
46# generation = model.generate(image_pt, input_id, max_new_tokens=256, do_sample=True, top_p=0.9, temperature=1.0)
47generation, seg_logit = model.generate(image_pt, input_id, seg_enable=True, max_new_tokens=256, do_sample=True, top_p=0.9, temperature=1.0)
48
49generated_texts = tokenizer.batch_decode(generation, skip_special_tokens=True)
50seg_mask = (torch.sigmoid(seg_logit) > 0.5) * 1.0
51
52print('question', question)
53print('generated_texts', generated_texts[0])
54
55image = sikt.GetImageFromArray(image_np)
56ssv.display(image)
57seg = sikt.GetImageFromArray(seg_mask.cpu().numpy()[0])
58ssv.display(seg)