|
|
|
from doctest import OutputChecker |
|
import sys |
|
import argparse |
|
|
|
import re |
|
import os |
|
import gradio as gr |
|
import requests |
|
from sentence_transformers import SentenceTransformer, util |
|
import torch |
|
from transformers import GPT2Tokenizer, GPT2LMHeadModel |
|
from transformers import T5Tokenizer, AutoModelForCausalLM |
|
import torch |
|
from doctest import OutputChecker |
|
import sys |
|
import torch |
|
import re |
|
import os |
|
import gradio as gr |
|
import requests |
|
import torch |
|
from transformers import GPT2Tokenizer, GPT2LMHeadModel |
|
from torch.nn.functional import softmax |
|
import numpy as np |
|
|
|
|
|
from transformers import BertJapaneseTokenizer, BertModel |
|
import torch |
|
|
|
|
|
class SentenceBertJapanese: |
|
def __init__(self, model_name_or_path, device=None): |
|
self.tokenizer = BertJapaneseTokenizer.from_pretrained(model_name_or_path) |
|
self.model = BertModel.from_pretrained(model_name_or_path) |
|
self.model.eval() |
|
|
|
if device is None: |
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
self.device = torch.device(device) |
|
self.model.to(device) |
|
|
|
def _mean_pooling(self, model_output, attention_mask): |
|
token_embeddings = model_output[0] |
|
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() |
|
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9) |
|
|
|
|
|
def encode(self, sentences, batch_size=8): |
|
all_embeddings = [] |
|
iterator = range(0, len(sentences), batch_size) |
|
for batch_idx in iterator: |
|
batch = sentences[batch_idx:batch_idx + batch_size] |
|
|
|
encoded_input = self.tokenizer.batch_encode_plus(batch, padding="longest", |
|
truncation=True, return_tensors="pt").to(self.device) |
|
model_output = self.model(**encoded_input) |
|
sentence_embeddings = self._mean_pooling(model_output, encoded_input["attention_mask"]).to('cpu') |
|
|
|
all_embeddings.extend(sentence_embeddings) |
|
|
|
|
|
return torch.stack(all_embeddings) |
|
|
|
|
|
|
|
|
|
model_sbert = SentenceTransformer("colorfulscoop/sbert-base-ja") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from transformers import GPT2Tokenizer, GPT2LMHeadModel |
|
import numpy as np |
|
import re |
|
|
|
def Sort_Tuple(tup): |
|
|
|
|
|
tup.sort(key = lambda x: x[1]) |
|
return tup[::-1] |
|
|
|
|
|
def softmax(x): |
|
exps = np.exp(x) |
|
return np.divide(exps, np.sum(exps)) |
|
|
|
|
|
|
|
|
|
|
|
|
|
tokenizer = T5Tokenizer.from_pretrained("rinna/japanese-gpt-1b") |
|
model = AutoModelForCausalLM.from_pretrained("rinna/japanese-gpt-1b") |
|
|
|
def sentence_prob_mean(text): |
|
|
|
input_ids = tokenizer.encode(text, return_tensors='pt') |
|
|
|
|
|
with torch.no_grad(): |
|
outputs = model(input_ids, labels=input_ids) |
|
logits = outputs.logits |
|
|
|
|
|
shift_logits = logits[..., :-1, :].contiguous() |
|
shift_labels = input_ids[..., 1:].contiguous() |
|
|
|
|
|
probs = softmax(shift_logits, dim=-1) |
|
|
|
|
|
gathered_probs = torch.gather(probs, 2, shift_labels.unsqueeze(-1)).squeeze(-1) |
|
|
|
|
|
mean_prob = torch.mean(gathered_probs).item() |
|
|
|
return mean_prob |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def cos_sim(a, b): |
|
return np.inner(a, b) / (np.linalg.norm(a) * (np.linalg.norm(b))) |
|
|
|
def get_sim(x): |
|
x = str(x)[1:-1] |
|
x = str(x)[1:-1] |
|
return x |
|
|
|
|
|
|
|
|
|
|
|
def Visual_re_ranker(sentence_man, sentence_woman, context_label, context_prob): |
|
sentence_man = sentence_man |
|
sentence_woman = sentence_woman |
|
context_label= context_label |
|
context_prob = context_prob |
|
sentence_emb_man = model_sbert.encode(sentence_man, convert_to_tensor=True) |
|
sentence_emb_woman = model_sbert.encode(sentence_woman, convert_to_tensor=True) |
|
context_label_emb = model_sbert.encode(context_label, convert_to_tensor=True) |
|
|
|
sim_m = cosine_scores = util.pytorch_cos_sim(sentence_emb_man, context_label_emb) |
|
sim_m = sim_m.cpu().numpy() |
|
sim_m = get_sim(sim_m) |
|
|
|
sim_w = cosine_scores = util.pytorch_cos_sim(sentence_emb_woman, context_label_emb) |
|
sim_w = sim_w.cpu().numpy() |
|
sim_w = get_sim(sim_w) |
|
|
|
|
|
LM_man = sentence_prob_mean(sentence_man) |
|
LM_woman = sentence_prob_mean(sentence_woman) |
|
|
|
|
|
|
|
|
|
score_man = pow(float(LM_man),pow((1-float(sim_m))/(1+ float(sim_m)),1-float(context_prob))) |
|
score_woman = pow(float(LM_woman),pow((1-float(sim_w))/(1+ float(sim_w)),1-float(context_prob))) |
|
|
|
|
|
|
|
|
|
|
|
return {"彼 (man)": float(score_man * 100000000), "彼女 (woman)": float(score_woman)* 1000000000} |
|
|
|
|
|
|
|
|
|
|
|
|
|
demo = gr.Interface( |
|
fn=Visual_re_ranker, |
|
description="Demo for Women Wearing Lipstick: Measuring the Bias Between Object and Its Related Gender", |
|
inputs=[gr.Textbox(value="ハイデルベルク大学は彼の出身大学である。") , gr.Textbox(value="ハイデルベルク大学は彼女の出身大学である。"), gr.Textbox(value="大学"), gr.Textbox(value="0.7458009")], |
|
|
|
|
|
|
|
|
|
|
|
outputs="label", |
|
) |
|
demo.launch() |
|
|