Views
No views yet
dbmdz/bert-base-turkish-128k-cased for classifying the acceptability of a Turkish text output given a Turkish text input.
It was developed as part of the "Evaluation of the Acceptability of Model Outputs" (May 2025).dbmdz/bert-base-turkish-128k-cased and achieved 88% accuracy on a manually curated Turkish test set.max_length of 64 tokens for the combined input and output. Longer texts will be truncated.1import torch
2from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
4TOKEN_KEY = "YOUR_HF_TOKEN_HERE" # Replace with your Hugging Face token or set to None
5MODEL_NAME = "helizac/pair-acceptability-turkish-large"
6
7device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
8MAX_LENGTH = 64
9
10_tokenizer_cache = {}
11
12def get_tokenizer(tokenizer_name: str, token: str = None):
13 if tokenizer_name not in _tokenizer_cache:
14 _tokenizer_cache[tokenizer_name] = AutoTokenizer.from_pretrained(tokenizer_name, token=token)
15 return _tokenizer_cache[tokenizer_name]
16
17def load_model_and_tokenizer(model_name: str, token: str = None):
18 tokenizer = get_tokenizer(model_name, token=token)
19 model = AutoModelForSequenceClassification.from_pretrained(model_name, token=token)
20 model.to(device)
21 model.eval()
22 return model, tokenizer
23
24def count_tokens(text: str, tokenizer_name: str, token: str = None, add_special_tokens: bool = False) -> int:
25 tokenizer = get_tokenizer(tokenizer_name, token=token)
26 encoded_input = tokenizer(text, add_special_tokens=add_special_tokens)
27 token_count = len(encoded_input['input_ids'])
28 return token_count
29
30def predict_pair_acceptability(input_text: str, output_text: str, model, tokenizer, device, max_length: int):
31 model.eval()
32
33 input_tok_count = count_tokens(input_text, tokenizer.name_or_path, token=TOKEN_KEY if TOKEN_KEY else None)
34 output_tok_count = count_tokens(output_text, tokenizer.name_or_path, token=TOKEN_KEY if TOKEN_KEY else None)
35
36 if input_tok_count + output_tok_count > max_length - 3: # Max length for content tokens
37 print(f"Warning: Input ({input_tok_count}) + Output ({output_tok_count}) tokens might exceed effective max_length ({max_length-3}). Truncation will occur, primarily on output.")
38
39 try:
40 encoding = tokenizer(text=input_text, text_pair=output_text, add_special_tokens=True, return_tensors='pt', max_length=max_length, padding='max_length', truncation=True)
41 input_ids = encoding['input_ids'].to(device)
42 attention_mask = encoding['attention_mask'].to(device)
43 token_type_ids = encoding.get('token_type_ids')
44
45 with torch.no_grad():
46 if token_type_ids is not None and model.config.model_type not in ['roberta']:
47 outputs = model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids.to(device))
48 else:
49 outputs = model(input_ids=input_ids, attention_mask=attention_mask)
50
51 logits = outputs.logits
52 probs = torch.softmax(logits, dim=-1)
53 prediction_index = torch.argmax(probs, dim=1).item()
54 confidence = probs[0, prediction_index].item()
55
56 label_map = {0: "kabul edilemez", 1: "kabul edilebilir"}
57 return label_map[prediction_index], confidence
58 except Exception as e:
59 print(f"Error during prediction for input '{input_text[:50]}...' / output '{output_text[:50]}...': {e}")
60 return f"Error: {e}", 0.0
61
62model, tokenizer = load_model_and_tokenizer(MODEL_NAME, token=TOKEN_KEY)
63
64# Example 1: Acceptable
65input_text_1 = "Dün satın aldığım kıyafeti beğendin mi?"
66output_text_1 = "Evet, çok güzel!"
67prediction_1, confidence_1 = predict_pair_acceptability(input_text_1, output_text_1, model, tokenizer, device, MAX_LENGTH)
68print(f"Input: {input_text_1}\nOutput: {output_text_1}\nPrediction: {prediction_1} (Confidence: {confidence_1:.4f})\n")
69
70# Example 2: Unacceptable (irrelevant)
71input_text_2 = "Dün satın aldığım kıyafeti beğendin mi?"
72output_text_2 = "Elmalar çok güzel!"
73prediction_2, confidence_2 = predict_pair_acceptability(input_text_2, output_text_2, model, tokenizer, device, MAX_LENGTH)
74print(f"Input: {input_text_2}\nOutput: {output_text_2}\nPrediction: {prediction_2} (Confidence: {confidence_2:.4f})\n")
75
76# Example 3: Unacceptable (grammatically poor)
77input_text_3 = "Hayalindeki meslek ne büyük."
78output_text_3 = "Olmak ben istemek büyük.
79prediction_3, confidence_3 = predict_pair_acceptability(input_text_3, output_text_3, model, tokenizer, device, MAX_LENGTH)
80print(f"Input: {input_text_3}\nOutput: {output_text_3}\nPrediction: {prediction_3} (Confidence: {confidence_3:.4f})\n")