mrmax14 commited on
Commit
7611348
·
1 Parent(s): a8594bc

new llama model added

Browse files
Files changed (1) hide show
  1. app.py +41 -67
app.py CHANGED
@@ -1,79 +1,53 @@
1
  import os
2
- import torch
3
- import json
4
  from transformers import LlamaTokenizer, LlamaForCausalLM
5
- import gradio as gr
6
- from huggingface_hub import login
7
-
8
- # Токен для доступу до Hugging Face Hub
9
- hf_token = os.getenv("HF_API_TOKEN")
10
- if not hf_token:
11
- raise ValueError("HF_API_TOKEN is not set or invalid.")
12
-
13
- # Логін до Hugging Face Hub
14
- login(token=hf_token)
15
 
16
- # Шлях до локального репозиторію з моделлю
17
- repo_path = "meta-llama/Llama-2-7b-chat"
18
- params_path = os.path.join(repo_path, "params.json")
19
- model_weights_path = os.path.join(repo_path, "consolidated.00.pth")
20
  config_path = os.path.join(repo_path, "config.json")
21
- tokenizer_path = repo_path # Папка, де зберігається `tokenizer.model`
22
-
23
- # Перевірка чи існує каталог, якщо ні - створення
24
- os.makedirs(repo_path, exist_ok=True)
25
 
26
- # Якщо файл конфігурації не існує, створюємо його
27
- if not os.path.exists(config_path):
28
- print(f"{config_path} not found. Creating custom config.json...")
29
- custom_config = {
30
- "architectures": ["LlamaForCausalLM"],
31
- "model_type": "llama",
32
- "hidden_size": 4096,
33
- "num_attention_heads": 32,
34
- "num_hidden_layers": 32,
35
- "vocab_size": 32000,
36
- "max_position_embeddings": 2048,
37
- "pad_token_id": 0,
38
- "bos_token_id": 1,
39
- "eos_token_id": 2
40
- }
41
 
42
- with open(config_path, "w") as f:
43
- json.dump(custom_config, f, indent=4)
44
- print(f"{config_path} created successfully!")
 
45
 
46
  # Завантаження токенізатора
47
- tokenizer = LlamaTokenizer.from_pretrained(tokenizer_path)
 
 
48
 
49
- # Завантаження стану моделі
50
- state_dict = torch.load(model_weights_path, map_location=torch.device("cpu"))
 
51
 
52
- # Завантаження конфігурації з вашого файлу
53
- with open(config_path, "r") as f:
54
- config = json.load(f)
55
-
56
- # Ініціалізація моделі
57
  model = LlamaForCausalLM.from_pretrained(
58
- pretrained_model_name_or_path=None,
59
- state_dict=state_dict,
60
- config=config
61
  )
62
-
63
- # Функція для генерації відповіді
64
- def generate_response(prompt):
65
- inputs = tokenizer(prompt, return_tensors="pt").to("cpu")
66
- outputs = model.generate(inputs.input_ids, max_length=200, temperature=0.7)
67
- return tokenizer.decode(outputs[0], skip_special_tokens=True)
68
-
69
- # Створення інтерфейсу Gradio
70
- demo = gr.Interface(
71
- fn=generate_response,
72
- inputs="text",
73
- outputs="text",
74
- title="LLaMA 2 Chatbot",
75
- description="Chatbot based on LLaMA 2 model."
76
- )
77
-
78
- if __name__ == "__main__":
79
- demo.launch()
 
 
 
 
1
  import os
 
 
2
  from transformers import LlamaTokenizer, LlamaForCausalLM
3
+ import torch
 
 
 
 
 
 
 
 
 
4
 
5
+ # Налаштування шляхів
6
+ repo_path = "meta-llama/Llama-2-7b-chat" # Локальний шлях до моделі
 
 
7
  config_path = os.path.join(repo_path, "config.json")
8
+ tokenizer_path = os.path.join(repo_path, "tokenizer.model")
 
 
 
9
 
10
+ # Перевірка наявності необхідних файлів
11
+ if not os.path.exists(repo_path):
12
+ raise FileNotFoundError(f"The specified repository path does not exist: {repo_path}")
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ required_files = ["config.json", "tokenizer.model", "consolidated.00.pth", "params.json"]
15
+ for file in required_files:
16
+ if not os.path.exists(os.path.join(repo_path, file)):
17
+ raise FileNotFoundError(f"Missing required file in {repo_path}: {file}")
18
 
19
  # Завантаження токенізатора
20
+ print("Loading tokenizer...")
21
+ tokenizer = LlamaTokenizer(vocab_file=tokenizer_path)
22
+ print("Tokenizer loaded successfully!")
23
 
24
+ # Завантаження моделі
25
+ print("Loading model...")
26
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
 
 
 
 
 
 
28
  model = LlamaForCausalLM.from_pretrained(
29
+ repo_path,
30
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
31
+ low_cpu_mem_usage=True,
32
  )
33
+ model = model.to(device)
34
+ print("Model loaded successfully!")
35
+
36
+ # Приклад використання
37
+ input_text = "Привіт! Як ти себе почуваєш сьогодні?"
38
+ inputs = tokenizer(input_text, return_tensors="pt").to(device)
39
+
40
+ print("Generating response...")
41
+ with torch.no_grad():
42
+ outputs = model.generate(
43
+ inputs["input_ids"],
44
+ max_length=100,
45
+ temperature=0.7,
46
+ top_k=50,
47
+ top_p=0.9,
48
+ do_sample=True,
49
+ )
50
+
51
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
52
+ print("Response:")
53
+ print(response)