Instructions to use NoNeet/TestSLM with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use NoNeet/TestSLM with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="NoNeet/TestSLM")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("NoNeet/TestSLM") model = AutoModelForSequenceClassification.from_pretrained("NoNeet/TestSLM", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Initial model push with fine-tuned RuBERT on Kinopoisk dataset and training script
Browse filesFiles changed (9)
- README.md+66-202
- final_model/NLP.pyAdded+225
- final_model/config.jsonAdded+38
- final_model/model.safetensorsAdded+3
- final_model/special_tokens_map.jsonAdded+7
- final_model/tokenizer.jsonAdded
- final_model/tokenizer_config.jsonAdded+58
- final_model/vocab.txtAdded
- model.safetensors+1-1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202---library_name: transformerstags:- unsloth- trl- sft---# Model Card for Model ID<!-- Provide a quick summary of what the model is/does. -->## Model Details### Model Description<!-- Provide a longer summary of what this model is. -->This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.- **Developed by:** [More Information Needed]- **Funded by [optional]:** [More Information Needed]- **Shared by [optional]:** [More Information Needed]- **Model type:** [More Information Needed]- **Language(s) (NLP):** [More Information Needed]- **License:** [More Information Needed]- **Finetuned from model [optional]:** [More Information Needed]### Model Sources [optional]<!-- Provide the basic links for the model. -->- **Repository:** [More Information Needed]- **Paper [optional]:** [More Information Needed]- **Demo [optional]:** [More Information Needed]## Uses<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->### Direct Use<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->[More Information Needed]### Downstream Use [optional]<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->[More Information Needed]### Out-of-Scope Use<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->[More Information Needed]## Bias, Risks, and Limitations<!-- This section is meant to convey both technical and sociotechnical limitations. -->[More Information Needed]### Recommendations<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.## How to Get Started with the ModelUse the code below to get started with the model.[More Information Needed]## Training Details### Training Data<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->[More Information Needed]### Training Procedure<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->#### Preprocessing [optional][More Information Needed]#### Training Hyperparameters- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->#### Speeds, Sizes, Times [optional]<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->[More Information Needed]## Evaluation<!-- This section describes the evaluation protocols and provides the results. -->### Testing Data, Factors & Metrics#### Testing Data<!-- This should link to a Dataset Card if possible. -->[More Information Needed]#### Factors<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->[More Information Needed]#### Metrics<!-- These are the evaluation metrics being used, ideally with a description of why. -->[More Information Needed]### Results[More Information Needed]#### Summary## Model Examination [optional]<!-- Relevant interpretability work for the model goes here -->[More Information Needed]## Environmental Impact<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).- **Hardware Type:** [More Information Needed]- **Hours used:** [More Information Needed]- **Cloud Provider:** [More Information Needed]- **Compute Region:** [More Information Needed]- **Carbon Emitted:** [More Information Needed]## Technical Specifications [optional]### Model Architecture and Objective[More Information Needed]### Compute Infrastructure[More Information Needed]#### Hardware[More Information Needed]#### Software[More Information Needed]## Citation [optional]<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->**BibTeX:**[More Information Needed]**APA:**[More Information Needed]## Glossary [optional]<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->[More Information Needed]## More Information [optional][More Information Needed]## Model Card Authors [optional][More Information Needed]## Model Card Contact[More Information Needed]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566---library_name: transformerslicense: apache-2.0base_model: sberbank-ai/rubert-basetags:- generated_from_trainermetrics:- accuracymodel-index:- name: TestSLMresults: []---<!-- This model card has been generated automatically according to the information the Trainer had access to. Youshould probably proofread and complete it, then remove this comment. --># TestSLMThis model is a fine-tuned version of [sberbank-ai/rubert-base](https://huggingface.co/sberbank-ai/rubert-base) on an unknown dataset.It achieves the following results on the evaluation set:- Loss: 0.2956- Accuracy: 0.971## Model descriptionMore information needed## Intended uses & limitationsMore information needed## Training and evaluation dataMore information needed## Training procedure### Training hyperparametersThe following hyperparameters were used during training:- learning_rate: 2e-05- train_batch_size: 8- eval_batch_size: 8- seed: 42- optimizer: Use OptimizerNames.ADAMW_TORCH_FUSED with betas=(0.9,0.999) and epsilon=1e-08 and optimizer_args=No additional optimizer arguments- lr_scheduler_type: linear- num_epochs: 5- mixed_precision_training: Native AMP### Training results| Training Loss | Epoch | Step | Validation Loss | Accuracy ||:-------------:|:-----:|:----:|:---------------:|:--------:|| 0.3106 | 1.0 | 500 | 0.5177 | 0.955 || 0.1336 | 2.0 | 1000 | 0.2956 | 0.971 || 0.0701 | 3.0 | 1500 | 0.3801 | 0.968 || 0.0003 | 4.0 | 2000 | 0.3441 | 0.971 || 0.0045 | 5.0 | 2500 | 0.3358 | 0.973 |### Framework versions- Transformers 4.57.0- Pytorch 2.9.0.dev20250628+cu128- Datasets 4.1.1- Tokenizers 0.22.1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225import numpy as np
from datasets import load_dataset
from transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
TrainingArguments,
Trainer,
pipeline,
PushToHubCallback
)
import evaluate
import torch
from torch.nn import CrossEntropyLoss
from sklearn.utils import compute_class_weight
import os
import shutil
print("Загрузка и разделение датасета 'blinoff/kinopoisk'...")
raw_dataset = load_dataset("blinoff/kinopoisk", split='train')
dataset_splits = raw_dataset.train_test_split(test_size=0.2, seed=42)
print("\nФильтрация датасета для бинарной классификации и преобразование меток...")
dataset_splits_filtered = dataset_splits.filter(lambda example: example['grade3'] != 'Neutral')
def map_labels(example):
if example['grade3'] == 'Good':
example['grade3'] = 1
elif example['grade3'] == 'Bad':
example['grade3'] = 0
return example
dataset_splits_mapped = dataset_splits_filtered.map(map_labels)
print("Выбор небольших подвыборок для демонстрации...")
train_dataset = dataset_splits_mapped["train"].shuffle(seed=42).select(range(4000))
eval_dataset = dataset_splits_mapped["test"].shuffle(seed=42).select(range(1000))
print("Данные отфильтрованы и преобразованы. Оставшиеся метки в train_dataset:", set(train_dataset['grade3']))
print("Данные отфильтрованы и преобразованы. Оставшиеся метки в eval_dataset:", set(eval_dataset['grade3']))
model_name = "sberbank-ai/rubert-base"
print(f"\nЗагрузка русской модели {model_name}...")
tokenizer = AutoTokenizer.from_pretrained(model_name)
id2label = {0: "НЕГАТИВНЫЙ", 1: "ПОЗИТИВНЫЙ"}
label2id = {"НЕГАТИВНЫЙ": 0, "ПОЗИТИВНЫЙ": 1}
model = AutoModelForSequenceClassification.from_pretrained(
model_name,
num_labels=2,
id2label=id2label,
label2id=label2id
)
def tokenize_function(examples):
return tokenizer(examples["content"], padding="max_length", truncation=True, max_length=512)
print("\nПрименение токенизатора к данным...")
tokenized_train_dataset = train_dataset.map(
tokenize_function,
batched=True,
)
tokenized_eval_dataset = eval_dataset.map(
tokenize_function,
batched=True,
)
tokenized_train_dataset = tokenized_train_dataset.rename_column("grade3", "labels")
tokenized_eval_dataset = tokenized_eval_dataset.rename_column("grade3", "labels")
required_columns = ['input_ids', 'attention_mask', 'labels']
if 'token_type_ids' in tokenized_train_dataset.column_names:
required_columns.append('token_type_ids')
else:
if tokenized_train_dataset and 'token_type_ids' in tokenized_train_dataset[0]:
required_columns.append('token_type_ids')
else:
print("Внимание: 'token_type_ids' не найдены в токенизированных данных.")
def cast_labels_to_long(examples):
return {"labels": torch.tensor(examples["labels"], dtype=torch.long)}
tokenized_train_dataset = tokenized_train_dataset.map(cast_labels_to_long, batched=True)
tokenized_eval_dataset = tokenized_eval_dataset.map(cast_labels_to_long, batched=True)
tokenized_train_dataset.set_format(type="torch", columns=required_columns)
tokenized_eval_dataset.set_format(type="torch", columns=required_columns)
print("\nКолонки в датасете после токенизации и очистки:")
print(tokenized_train_dataset.column_names)
print("\nРасчет весов классов для устранения дисбаланса...")
train_labels_np = np.array(tokenized_train_dataset['labels'])
class_weights = compute_class_weight(
class_weight='balanced',
classes=np.unique(train_labels_np),
y=train_labels_np
)
class_weights = torch.tensor(class_weights, dtype=torch.float)
print(f"Вычисленные веса классов: {class_weights}")
metric = evaluate.load("accuracy")
def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return metric.compute(predictions=predictions, references=labels)
class CustomTrainer(Trainer):
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
labels = inputs.pop("labels")
outputs = model(**inputs)
logits = outputs.get("logits")
loss_fct = CrossEntropyLoss(weight=class_weights.to(logits.device))
loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
return (loss, outputs) if return_outputs else loss
print("\nНастройка и запуск процесса обучения...")
output_dir = "kinopoisk_rubert_fine_tuned"
repo_name = "NoNeet/TestSLM"
training_args = TrainingArguments(
output_dir=output_dir,
num_train_epochs=5,
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
logging_steps=100,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
report_to="none",
fp16=torch.cuda.is_available(),
learning_rate=2e-5,
push_to_hub=True,
hub_model_id=repo_name,
)
trainer = CustomTrainer(
model=model,
args=training_args,
train_dataset=tokenized_train_dataset,
eval_dataset=tokenized_eval_dataset,
compute_metrics=compute_metrics,
tokenizer=tokenizer
)
trainer.train()
print("\nИтоговая оценка модели на тестовом наборе:")
evaluation_results = trainer.evaluate()
print(f"Точность (Accuracy): {evaluation_results['eval_accuracy']:.4f}")
print("\nМодель обучена и готова к использованию!")
final_model_path = os.path.join(output_dir, "final_model")
print(f"\nСохранение модели и токенизатора в {final_model_path}...")
trainer.model.save_pretrained(final_model_path)
tokenizer.save_pretrained(final_model_path)
current_script_path = os.path.abspath(__file__)
destination_script_path = os.path.join(final_model_path, os.path.basename(current_script_path))
shutil.copyfile(current_script_path, destination_script_path)
print(f"Скрипт '{os.path.basename(current_script_path)}' сохранен в {destination_script_path}")
print("Модель и токенизатор успешно сохранены.")
print("\nЗагрузка модели на Hugging Face Hub...")
trainer.push_to_hub(commit_message="Initial model push with fine-tuned RuBERT on Kinopoisk dataset and training script")
print(f"Модель успешно загружена на Hugging Face Hub: https://huggingface.co/{repo_name}")
print(f"\nЗагрузка модели из {final_model_path} для тестирования...")
loaded_tokenizer = AutoTokenizer.from_pretrained(final_model_path)
loaded_model = AutoModelForSequenceClassification.from_pretrained(final_model_path)
classifier = pipeline(
"text-classification",
model=loaded_model,
tokenizer=loaded_tokenizer,
device=0 if torch.cuda.is_available() else -1,
)
positive_review = "Это лучший фильм, который я видел в этом году! Сюжет, актеры, музыка - все на высоте."
negative_review = "Полное разочарование. Непонятно, на что ушли деньги. Не советую смотреть."
mixed_review = "Фильм неплох, но конец немного подкачал."
neutral_review = "Обычный фильм, ничего особенного."
very_negative_review = "Худший фильм года, просто ужас. Пустая трата времени и денег."
very_positive_review = "Шедевр! Актерская игра просто невероятна, сюжет держит в напряжении до последней секунды."
sarcastic_review = "Конечно, это лучший фильм! Особенно если любишь скуку и отсутствие логики."
ambiguous_review = "Не могу сказать, что фильм плох, но и хорошим его не назовешь."
print(f"\nОтзыв: '{positive_review}'")
print(f"Результат: {classifier(positive_review)}")
print(f"\nОтзыв: '{negative_review}'")
print(f"Результат: {classifier(negative_review)}")
print(f"\nОтзыв: '{mixed_review}'")
print(f"Результат: {classifier(mixed_review)}")
print(f"\nОтзыв: '{neutral_review}'")
print(f"Результат: {classifier(neutral_review)}")
print(f"\nОтзыв: '{very_negative_review}'")
print(f"Результат: {classifier(very_negative_review)}")
print(f"\nОтзыв: '{very_positive_review}'")
print(f"Результат: {classifier(very_positive_review)}")
print(f"\nОтзыв: '{sarcastic_review}'")
print(f"Результат: {classifier(sarcastic_review)}")
print(f"\nОтзыв: '{ambiguous_review}'")
print(f"Результат: {classifier(ambiguous_review)}")
print("\n--- Финальная проверка распределения меток в датасетах для обучения ---")
print("Проверка распределения меток в tokenized_train_dataset:")
train_labels = tokenized_train_dataset['labels']
unique_train_labels, counts_train = np.unique(train_labels, return_counts=True)
print(f"Уникальные метки в тренировочном наборе: {unique_train_labels}, Распределение: {dict(zip(unique_train_labels, counts_train))}")
print("\nПроверка распределения меток в tokenized_eval_dataset:")
eval_labels = tokenized_eval_dataset['labels']
unique_eval_labels, counts_eval = np.unique(eval_labels, return_counts=True)
print(f"Уникальные метки в валидационном наборе: {unique_eval_labels}, Распределение: {dict(zip(unique_eval_labels, counts_eval))}")
print("\nНастройки меток в модели перед обучением (взяты из model.config):")
print("model.config.id2label:", model.config.id2label)
print("model.config.label2id:", model.config.label2id)1234567891011121314151617181920212223242526272829303132333435363738{
"architectures": [
"BertForSequenceClassification"
],
"attention_probs_dropout_prob": 0.1,
"classifier_dropout": null,
"directionality": "bidi",
"dtype": "float32",
"hidden_act": "gelu",
"hidden_dropout_prob": 0.1,
"hidden_size": 768,
"id2label": {
"0": "\u041d\u0415\u0413\u0410\u0422\u0418\u0412\u041d\u042b\u0419",
"1": "\u041f\u041e\u0417\u0418\u0422\u0418\u0412\u041d\u042b\u0419"
},
"initializer_range": 0.02,
"intermediate_size": 3072,
"label2id": {
"\u041d\u0415\u0413\u0410\u0422\u0418\u0412\u041d\u042b\u0419": 0,
"\u041f\u041e\u0417\u0418\u0422\u0418\u0412\u041d\u042b\u0419": 1
},
"layer_norm_eps": 1e-12,
"max_position_embeddings": 512,
"model_type": "bert",
"num_attention_heads": 12,
"num_hidden_layers": 12,
"pad_token_id": 0,
"pooler_fc_size": 768,
"pooler_num_attention_heads": 12,
"pooler_num_fc_layers": 3,
"pooler_size_per_head": 128,
"pooler_type": "first_token_transform",
"position_embedding_type": "absolute",
"transformers_version": "4.57.0",
"type_vocab_size": 2,
"use_cache": true,
"vocab_size": 120138
}123version https://git-lfs.github.com/spec/v1oid sha256:6400c2462fab85c65a51254fe5c0ebf079ea586a27597014b76227fd0d2fdc70size 7132590081234567{
"cls_token": "[CLS]",
"mask_token": "[MASK]",
"pad_token": "[PAD]",
"sep_token": "[SEP]",
"unk_token": "[UNK]"
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758{
"added_tokens_decoder": {
"0": {
"content": "[PAD]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"100": {
"content": "[UNK]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"101": {
"content": "[CLS]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"102": {
"content": "[SEP]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"103": {
"content": "[MASK]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
}
},
"clean_up_tokenization_spaces": true,
"cls_token": "[CLS]",
"do_basic_tokenize": true,
"do_lower_case": true,
"extra_special_tokens": {},
"mask_token": "[MASK]",
"model_max_length": 1000000000000000019884624838656,
"never_split": null,
"pad_token": "[PAD]",
"sep_token": "[SEP]",
"strip_accents": null,
"tokenize_chinese_chars": true,
"tokenizer_class": "BertTokenizer",
"unk_token": "[UNK]"
}123version https://git-lfs.github.com/spec/v1oid sha256:e6323639c1b84aa44660046400bc18da8aad2bdce0d4a9110a726dc0c41d74f1size 713259008123version https://git-lfs.github.com/spec/v1oid sha256:6400c2462fab85c65a51254fe5c0ebf079ea586a27597014b76227fd0d2fdc70size 713259008
README.md+66-202
final_model/NLP.pyAdded+225
final_model/config.jsonAdded+38
final_model/model.safetensorsAdded+3
final_model/special_tokens_map.jsonAdded+7
final_model/tokenizer.jsonAdded
final_model/tokenizer_config.jsonAdded+58
final_model/vocab.txtAdded
model.safetensors+1-1