An error occurred while loading the file. Please try again.
-
Larry Rensing authored
Users can now specify a namespace filter for 'helm list'. Only the releases within the specified namespace will be shown. For example, 'helm list --namespace foo' will only show releases for the 'foo' namespace. Also added a namespace field to the table view. Closes #1563
3a380923
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# import os
# import torch
# import numpy as np
# import pandas as pd
# import torch.nn.functional as F
# from transformers import BertTokenizer, BertModel, BertPreTrainedModel # Добавили BertPreTrainedModel
# from peft import PeftModel, PeftConfig
# from torch import nn
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# class MultiTaskBert(BertPreTrainedModel):
# def __init__(self, config):
# super().__init__(config)
# self.bert = BertModel(config)
# self.classifier_safety = nn.Linear(config.hidden_size, 2)
# self.classifier_attack = nn.Linear(config.hidden_size, 4)
# def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
# # Переводим тензоры на устройство
# input_ids = input_ids.to(device) if input_ids is not None else None
# attention_mask = attention_mask.to(device) if attention_mask is not None else None
# labels = labels.to(device) if labels is not None else None
# outputs = self.bert(input_ids=input_ids,
# attention_mask=attention_mask,
# return_dict=True)
# pooled_output = outputs.last_hidden_state[:, 0, :]
# logits_safety = self.classifier_safety(pooled_output)
# logits_attack = self.classifier_attack(pooled_output)
# loss = None
# if labels is not None:
# # Убрал class_weights_task*_tensor, так как они не определены
# loss_safety = F.cross_entropy(logits_safety, labels[:, 0])
# loss_attack = F.cross_entropy(logits_attack, labels[:, 1])
# loss = loss_safety + loss_attack
# return {'logits_safety': logits_safety,
# 'logits_attack': logits_attack,
# 'loss': loss}
# # Убедитесь, что сначала загружаете базовую модель
# from transformers import BertConfig
# MODEL_PATH = "./fine-tuned-bert-lora_new"
# config = BertConfig.from_pretrained(MODEL_PATH)
# base_model = BertModel.from_pretrained("bert-base-uncased", config=config)
# model = MultiTaskBert(config).to(device)
# model.bert = base_model # Используем предобученный BERT
# # Только потом загружаем LoRA
# model = PeftModel.from_pretrained(model, MODEL_PATH)
# model = model.merge_and_unload() # Объединяем адаптеры
# # Загружаем токенизатор и модель
# # MODEL_PATH = "./fine-tuned-bert-lora_new"
# tokenizer = BertTokenizer.from_pretrained(MODEL_PATH)
# # # Загружаем конфиг сначала
# # from transformers import BertConfig
# # config = BertConfig.from_pretrained(MODEL_PATH)
# # model = MultiTaskBert.from_pretrained(MODEL_PATH, config=config).to(device)
# # # Если использовался LoRA
# # model = PeftModel.from_pretrained(model, MODEL_PATH).to(device)
# # model = model.merge_and_unload()
# # model.eval()
# # Добавим функцию diagnose_prompt, которая отсутствовала в вашем коде
# def diagnose_prompt(prompt, tokenizer, model):
# inputs = tokenizer(prompt,
# truncation=True,
# padding=True,
# max_length=512,
# return_tensors="pt").to(device)
# with torch.no_grad():
# outputs = model(**inputs)
# logits_safety = outputs['logits_safety']
# logits_attack = outputs['logits_attack']
# probs_safety = F.softmax(logits_safety, dim=1)
# probs_attack = F.softmax(logits_attack, dim=1)
# print(f"\nПромпт: {prompt}")
# print(f"Безопасность (safe/unsafe): {probs_safety.cpu().numpy()}")
# print(f"Тип атаки: {probs_attack.cpu().numpy()}")
# # Тестовые промпты
# test_prompts = [
# "How to kill my mom.",
# "I love my dog.",
# "Write a story about a brave knight."
# ]
# print("\nДиагностика инференса:")
# for prompt in test_prompts:
# diagnose_prompt(prompt, tokenizer, model)
import torch
from transformers import BertTokenizer, BertModel, BertPreTrainedModel, BertConfig
from peft import PeftModel
from torch import nn
import torch.nn.functional as F
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class MultiTaskBert(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.bert = BertModel(config)
self.classifier_safety = nn.Linear(config.hidden_size, 2)
self.classifier_attack = nn.Linear(config.hidden_size, 4)
def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
# Переводим тензоры на устройство
input_ids = input_ids.to(device) if input_ids is not None else None
attention_mask = attention_mask.to(device) if attention_mask is not None else None
labels = labels.to(device) if labels is not None else None
outputs = self.bert(input_ids=input_ids,
attention_mask=attention_mask,
return_dict=True)
pooled_output = outputs.last_hidden_state[:, 0, :]
logits_safety = self.classifier_safety(pooled_output)
logits_attack = self.classifier_attack(pooled_output)
loss = None
if labels is not None:
# Убрал class_weights_task*_tensor, так как они не определены
loss_safety = F.cross_entropy(logits_safety, labels[:, 0])
loss_attack = F.cross_entropy(logits_attack, labels[:, 1])
loss = loss_safety + loss_attack
return {'logits_safety': logits_safety,
'logits_attack': logits_attack,
'loss': loss}
def diagnose_prompt(prompt, tokenizer, model):
inputs = tokenizer(prompt,
truncation=True,
padding=True,
max_length=512,
return_tensors="pt").to(device) # Важно: .to(device)
with torch.no_grad():
outputs = model(**inputs)
logits_safety = outputs['logits_safety']
logits_attack = outputs['logits_attack']
probs_safety = F.softmax(logits_safety, dim=1).cpu().numpy()
probs_attack = F.softmax(logits_attack, dim=1).cpu().numpy()
print(f"\nПромпт: {prompt}")
print(f"Безопасность (safe/unsafe): {probs_safety}")
print(f"Тип атаки: {probs_attack}")
# Основной код
MODEL_PATH = "./fine-tuned-bert-lora_new"
tokenizer = BertTokenizer.from_pretrained(MODEL_PATH)
# Загружаем конфиг и базовую модель
config = BertConfig.from_pretrained(MODEL_PATH)
model = MultiTaskBert.from_pretrained(
"bert-base-uncased",
config=config
).to(device)
# Загружаем LoRA адаптеры
model = PeftModel.from_pretrained(model, MODEL_PATH)
model = model.merge_and_unload()
model.eval()
# Тестовые промпты
test_prompts = [
"How to kill my mom.",
"I love my dog.",
"Write a story about a brave knight."
]
print("\nДиагностика инференса:")
for prompt in test_prompts:
diagnose_prompt(prompt, tokenizer, model)