Spaces:
Sleeping
Sleeping
File size: 4,627 Bytes
ae3a47c |
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 |
#ํ์ ํจํค์ง ์ค์น
!pip install mxnet
!pip install gluonnlp==0.8.0
!pip install tqdm pandas
!pip install sentencepiece
!pip install transformers
!pip install torch
!pip install numpy==1.23.1
#KoBERT ๊นํ๋ธ์์ ๋ถ๋ฌ์ค๊ธฐ
!pip install 'git+https://github.com/SKTBrain/KoBERT.git#egg=kobert_tokenizer&subdirectory=kobert_hf'
!pip install langchain==0.0.125 chromadb==0.3.14 pypdf==3.7.0 tiktoken==0.3.3
!pip install openai==0.28
!pip install gradio transformers torch opencv-python-headless
# import torch
from torch import nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import gluonnlp as nlp
import numpy as np
from tqdm import tqdm, tqdm_notebook
import pandas as pd
# Hugging Face๋ฅผ ํตํ ๋ชจ๋ธ ๋ฐ ํ ํฌ๋์ด์ Import
from kobert_tokenizer import KoBERTTokenizer
from transformers import BertModel
from transformers import AdamW
from transformers.optimization import get_cosine_schedule_with_warmup
n_devices = torch.cuda.device_count()
print(n_devices)
for i in range(n_devices):
print(torch.cuda.get_device_name(i))
if torch.cuda.is_available():
device = torch.device("cuda")
print('There are %d GPU(s) available.' % torch.cuda.device_count())
print('We will use the GPU:', torch.cuda.get_device_name(0))
else:
device = torch.device("cpu")
print('No GPU available, using the CPU instead.')
# Kobert_softmax
class BERTClassifier(nn.Module):
def __init__(self,
bert,
hidden_size=768,
num_classes=6,
dr_rate=None,
params=None):
super(BERTClassifier, self).__init__()
self.bert = bert
self.dr_rate = dr_rate
self.softmax = nn.Softmax(dim=1) # Softmax๋ก ๋ณ๊ฒฝ
self.classifier = nn.Sequential(
nn.Dropout(p=0.5),
nn.Linear(in_features=hidden_size, out_features=512),
nn.Linear(in_features=512, out_features=num_classes),
)
# ์ ๊ทํ ๋ ์ด์ด ์ถ๊ฐ (Layer Normalization)
self.layer_norm = nn.LayerNorm(768)
# ๋๋กญ์์
self.dropout = nn.Dropout(p=dr_rate)
def gen_attention_mask(self, token_ids, valid_length):
attention_mask = torch.zeros_like(token_ids)
for i, v in enumerate(valid_length):
attention_mask[i][:v] = 1
return attention_mask.float()
def forward(self, token_ids, valid_length, segment_ids):
attention_mask = self.gen_attention_mask(token_ids, valid_length)
_, pooler = self.bert(input_ids=token_ids, token_type_ids=segment_ids.long(), attention_mask=attention_mask.float().to(token_ids.device))
pooled_output = self.dropout(pooler)
normalized_output = self.layer_norm(pooled_output)
out = self.classifier(normalized_output)
# LayerNorm ์ ์ฉ
pooler = self.layer_norm(pooler)
if self.dr_rate:
pooler = self.dropout(pooler)
logits = self.classifier(pooler) # ๋ถ๋ฅ๋ฅผ ์ํ ๋ก์ง ๊ฐ ๊ณ์ฐ
probabilities = self.softmax(logits) # Softmax๋ก ๊ฐ ํด๋์ค์ ํ๋ฅ ๊ณ์ฐ
return probabilities # ๊ฐ ํด๋์ค์ ๋ํ ํ๋ฅ ๋ฐํ
#์ ์ํ ๋ชจ๋ธ ๋ถ๋ฌ์ค๊ธฐ
model = BERTClassifier(bertmodel,dr_rate=0.4).to(device)
#model = BERTClassifier(bertmodel, dr_rate=0.5).to('cpu')
# Prepare optimizer and schedule (linear warmup and decay)
no_decay = ['bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
{'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
optimizer = AdamW(optimizer_grouped_parameters, lr=learning_rate)
loss_fn = nn.CrossEntropyLoss()
t_total = len(train_dataloader) * num_epochs
warmup_step = int(t_total * warmup_ratio)
scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=warmup_step, num_training_steps=t_total)
def calc_accuracy(X,Y):
max_vals, max_indices = torch.max(X, 1)
train_acc = (max_indices == Y).sum().data.cpu().numpy()/max_indices.size()[0]
return train_acc
train_dataloader
model = torch.load('./model_weights_softmax(model).pth')
model.eval()
#gradio
!pip install --upgrade gradio
import numpy as np
import pandas as pd
import requests
from PIL import Image
import torch
from transformers import AutoProcessor, AutoModelForZeroShotImageClassification, pipeline
import gradio as gr
import openai
from sklearn.metrics.pairwise import cosine_similarity
import ast |