Spaces:
Build error
Build error
File size: 9,659 Bytes
2153792 |
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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
import os
from typing import Optional, Union, Tuple, Dict, Any, Literal
import numpy as np
try:
import tensorflow as tf
from tensorflow.keras import layers, models, optimizers, callbacks
from tensorflow.keras.models import Model
from tensorflow.keras.layers import (
Input, Embedding, Dense, Dropout, GlobalMaxPooling1D,
Conv1D, LSTM, GRU, Bidirectional, Attention, GlobalAveragePooling1D
)
TF_AVAILABLE = True
except ImportError:
TF_AVAILABLE = False
try:
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_sequence
from transformers import (
AutoTokenizer, AutoModel, AutoConfig,
BertForSequenceClassification, RobertaForSequenceClassification,
DistilBertForSequenceClassification, Trainer, TrainingArguments
)
from transformers.tokenization_utils_base import BatchEncoding
TORCH_AVAILABLE = True
except ImportError:
TORCH_AVAILABLE = False
class AttentionLayer(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def build(self, input_shape):
self.W = self.add_weight(
shape=(input_shape[-1], 1),
initializer='random_normal',
trainable=True,
name='attention_weight'
)
self.b = self.add_weight(
shape=(input_shape[1], 1),
initializer='zeros',
trainable=True,
name='attention_bias'
)
super().build(input_shape)
def call(self, inputs, **kwargs):
e = tf.keras.activations.tanh(tf.matmul(inputs, self.W) + self.b)
e = tf.squeeze(e, axis=-1)
a = tf.nn.softmax(e, axis=1)
a = tf.expand_dims(a, axis=-1)
weighted_input = inputs * a
return tf.reduce_sum(weighted_input, axis=1)
def build_mlp(
input_dim: int,
num_classes: int,
hidden_dims: list = [256, 128],
dropout: float = 0.3,
activation: str = 'relu'
) -> 'tf.keras.Model':
if not TF_AVAILABLE:
raise ImportError("TensorFlow not available")
inputs = Input(shape=(input_dim,))
x = inputs
for dim in hidden_dims:
x = Dense(dim, activation=activation)(x)
x = Dropout(dropout)(x)
outputs = Dense(num_classes, activation='softmax' if num_classes > 2 else 'sigmoid')(x)
return models.Model(inputs, outputs)
def build_kim_cnn(
max_len: int,
vocab_size: int,
embed_dim: int,
num_classes: int,
filter_sizes: list = [3, 4, 5],
num_filters: int = 100,
dropout: float = 0.5,
pre_embed_matrix: Optional[np.ndarray] = None
) -> 'tf.keras.Model':
if not TF_AVAILABLE:
raise ImportError("TensorFlow not available")
inputs = Input(shape=(max_len,))
if pre_embed_matrix is not None:
embedding = Embedding(
vocab_size, embed_dim,
weights=[pre_embed_matrix],
trainable=False
)(inputs)
else:
embedding = Embedding(vocab_size, embed_dim)(inputs)
pooled_outputs = []
for fs in filter_sizes:
x = Conv1D(num_filters, fs, activation='relu')(embedding)
x = GlobalMaxPooling1D()(x)
pooled_outputs.append(x)
merged = tf.concat(pooled_outputs, axis=1)
x = Dropout(dropout)(merged)
outputs = Dense(num_classes, activation='softmax' if num_classes > 2 else 'sigmoid')(x)
return models.Model(inputs, outputs)
def build_lstm(
max_len: int,
vocab_size: int,
embed_dim: int,
num_classes: int,
lstm_units: int = 128,
dropout: float = 0.3,
bidirectional: bool = False,
pre_embed_matrix: Optional[np.ndarray] = None
) -> 'tf.keras.Model':
if not TF_AVAILABLE:
raise ImportError("TensorFlow not available")
inputs = Input(shape=(max_len,))
if pre_embed_matrix is not None:
x = Embedding(vocab_size, embed_dim, weights=[pre_embed_matrix], trainable=False)(inputs)
else:
x = Embedding(vocab_size, embed_dim)(inputs)
rnn_layer = LSTM(lstm_units, dropout=dropout, recurrent_dropout=dropout)
if bidirectional:
x = Bidirectional(rnn_layer)(x)
else:
x = rnn_layer(x)
outputs = Dense(num_classes, activation='softmax' if num_classes > 2 else 'sigmoid')(x)
return models.Model(inputs, outputs)
def build_cnn_lstm(
max_len: int,
vocab_size: int,
embed_dim: int,
num_classes: int,
filter_size: int = 3,
num_filters: int = 128,
lstm_units: int = 64,
dropout: float = 0.3,
pre_embed_matrix: Optional[np.ndarray] = None
) -> 'tf.keras.Model':
if not TF_AVAILABLE:
raise ImportError("TensorFlow not available")
inputs = Input(shape=(max_len,))
if pre_embed_matrix is not None:
x = Embedding(vocab_size, embed_dim, weights=[pre_embed_matrix], trainable=False)(inputs)
else:
x = Embedding(vocab_size, embed_dim)(inputs)
x = Conv1D(num_filters, filter_size, activation='relu', padding='same')(x)
x = LSTM(lstm_units, dropout=dropout)(x)
outputs = Dense(num_classes, activation='softmax' if num_classes > 2 else 'sigmoid')(x)
return models.Model(inputs, outputs)
def build_birnn_attention(
max_len: int,
vocab_size: int,
embed_dim: int,
num_classes: int,
rnn_units: int = 64,
dropout: float = 0.3,
pre_embed_matrix: Optional[np.ndarray] = None
) -> 'tf.keras.Model':
if not TF_AVAILABLE:
raise ImportError("TensorFlow not available")
inputs = Input(shape=(max_len,))
if pre_embed_matrix is not None:
x = Embedding(vocab_size, embed_dim, weights=[pre_embed_matrix], trainable=False)(inputs)
else:
x = Embedding(vocab_size, embed_dim)(inputs)
x = Bidirectional(LSTM(rnn_units, return_sequences=True, dropout=dropout))(x)
x = AttentionLayer()(x)
outputs = Dense(num_classes, activation='softmax' if num_classes > 2 else 'sigmoid')(x)
return models.Model(inputs, outputs)
_RUSSIAN_TRANSFORMERS = {
"rubert": "DeepPavlov/rubert-base-cased",
"ruroberta": "sberbank-ai/ruRoberta-large",
"distilbert-multilingual": "distilbert-base-multilingual-cased"
}
def get_transformer_classifier(
model_name: str = "rubert",
num_classes: int = 2,
problem_type: Literal["single_label", "multi_label"] = "single_label"
) -> Tuple[Any, Any]:
if not TORCH_AVAILABLE:
raise ImportError("PyTorch or transformers not available")
if model_name not in _RUSSIAN_TRANSFORMERS:
raise ValueError(f"Unknown model_name. Choose from: {list(_RUSSIAN_TRANSFORMERS.keys())}")
model_id = _RUSSIAN_TRANSFORMERS[model_name]
tokenizer = AutoTokenizer.from_pretrained(model_id)
if "roberta" in model_id.lower():
model = RobertaForSequenceClassification.from_pretrained(
model_id, num_labels=num_classes
)
elif "distilbert" in model_id.lower():
model = DistilBertForSequenceClassification.from_pretrained(
model_id, num_labels=num_classes
)
else:
model = BertForSequenceClassification.from_pretrained(
model_id, num_labels=num_classes
)
if problem_type == "multi_label":
model.config.problem_type = "multi_label_classification"
else:
model.config.problem_type = "single_label_classification"
return model, tokenizer
def quantize_pytorch_model(model: 'torch.nn.Module', backend: str = "qnnpack") -> 'torch.nn.Module':
if not TORCH_AVAILABLE:
raise ImportError("PyTorch not available")
model.eval()
model.qconfig = torch.quantization.get_default_qconfig(backend)
torch.quantization.prepare(model, inplace=True)
torch.quantization.convert(model, inplace=True)
return model
def prune_keras_model(model: 'tf.keras.Model', sparsity: float = 0.5) -> 'tf.keras.Model':
try:
import tensorflow_model_optimization as tfmot
except ImportError:
raise ImportError("Install tensorflow-model-optimization for pruning")
pruning_params = {
'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(
initial_sparsity=0.0, final_sparsity=sparsity, begin_step=0, end_step=1000
)
}
model_for_pruning = tfmot.sparsity.keras.prune_low_magnitude(model, **pruning_params)
return model_for_pruning
def prepare_keras_inputs(
texts: list,
tokenizer=None,
max_len: int = 128,
vocab: Optional[dict] = None
) -> np.ndarray:
if tokenizer is not None:
encodings = tokenizer(texts, truncation=True, padding=True, max_length=max_len, return_tensors="np")
return encodings['input_ids']
else:
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
tk = Tokenizer(oov_token="<OOV>")
if vocab:
tk.word_index = vocab
else:
tk.fit_on_texts(texts)
sequences = tk.texts_to_sequences(texts)
return pad_sequences(sequences, maxlen=max_len)
def compile_keras_model(
model: 'tf.keras.Model',
learning_rate: float = 2e-5,
num_classes: int = 2
):
loss = 'sparse_categorical_crossentropy' if num_classes > 2 else 'binary_crossentropy'
model.compile(
optimizer=optimizers.Adam(learning_rate=learning_rate),
loss=loss,
metrics=['accuracy']
)
return model |