Spaces:
Sleeping

Mehreen44 commited on
Commit
31e24cc
·
verified ·
1 Parent(s): e667ae5

Delete utils/llm_loader

Browse files
Files changed (1) hide show
  1. utils/llm_loader +0 -68
utils/llm_loader DELETED
@@ -1,68 +0,0 @@
1
- import os
2
- import torch
3
- import streamlit as st
4
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
5
-
6
- @st.cache_resource
7
- def get_qwen_pipeline():
8
- """
9
- Loads Qwen/Qwen2.5-1.5B-Instruct and wraps it in a transformers pipeline.
10
- Utilizes CUDA if available, otherwise runs on CPU with memory optimizations.
11
- Uses @st.cache_resource to prevent reloading the model on every streamlit rerun.
12
- """
13
- model_name = "Qwen/Qwen2.5-1.5B-Instruct"
14
-
15
- # Check GPU availability
16
- if torch.cuda.is_available():
17
- device_map = "auto"
18
- torch_dtype = torch.float16
19
- print("GPU detected. Loading Qwen on CUDA...")
20
- else:
21
- device_map = None
22
- torch_dtype = torch.float32
23
- print("No GPU detected. Loading Qwen on CPU...")
24
-
25
- try:
26
- tokenizer = AutoTokenizer.from_pretrained(model_name)
27
- # Ensure pad token is set
28
- if tokenizer.pad_token is None:
29
- tokenizer.pad_token = tokenizer.eos_token
30
-
31
- model = AutoModelForCausalLM.from_pretrained(
32
- model_name,
33
- torch_dtype=torch_dtype,
34
- device_map=device_map,
35
- low_cpu_mem_usage=True
36
- )
37
-
38
- # If CPU, set device explicitly in pipeline; otherwise device_map handles it
39
- pipe_device = -1 if device_map is None else None
40
-
41
- pipe = pipeline(
42
- "text-generation",
43
- model=model,
44
- tokenizer=tokenizer,
45
- max_new_tokens=512,
46
- temperature=0.2,
47
- top_p=0.9,
48
- do_sample=True,
49
- device=pipe_device,
50
- pad_token_id=tokenizer.eos_token_id
51
- )
52
- return pipe
53
- except Exception as e:
54
- print(f"Failed to load model {model_name}: {str(e)}")
55
- raise RuntimeError(f"Model load error: {str(e)}")
56
-
57
- def generate_answer(prompt: str) -> str:
58
- """
59
- Generates a response from the Qwen model given a formatted prompt.
60
- Splits the generated text to return only the model's new response.
61
- """
62
- pipe = get_qwen_pipeline()
63
- try:
64
- outputs = pipe(prompt, return_full_text=False)
65
- return outputs[0]["generated_text"].strip()
66
- except Exception as e:
67
- print(f"Error during generation: {str(e)}")
68
- raise RuntimeError(f"Text generation failed: {str(e)}")