i get this error: Epoch 1: 0% 0/1 [00:00<?,…
- User
i get this error: Epoch 1: 0%| | 0/1 [00:00<?, ?it/s]C:\Users\L14\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\optim\lr_scheduler.py:152: UserWarning: The epoch parameter in
scheduler.step()was not necessary and is being deprecated where possible. Please usescheduler.step()to step the scheduler. During the deprecation, if epoch is different from None, the closed form is used instead of the new chainable form, where available. Please open an issue if you are unable to replicate your use case: https://github.com/pytorch/pytorch/issues/new/choose. warnings.warn(EPOCH_DEPRECATION_WARNING, UserWarning) Epoch 1, Average Loss: 5.066798 when i run this code: import os import torch import torch.nn as nn import torch.nn.functional as F import json import math from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader, Dataset from tqdm import tqdm import matplotlib.pyplot as plt from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score from tokenizers import Tokenizer from torch.optim.lr_scheduler import SequentialLR, StepLR, LinearLR---------- Device Configuration ----------
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
---------- Utility Functions ----------
def positional_encoding(seq_len, d_model, device): pos = torch.arange(seq_len, dtype=torch.float, device=device).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)).to(device) pe = torch.zeros(seq_len, d_model, device=device) pe[:, 0::2] = torch.sin(pos * div_term) pe[:, 1::2] = torch.cos(pos * div_term) return pe.unsqueeze(0)
-------- Performance ----------
def evaluate_model(model, data_loader, device): model.eval() all_preds, all_targets = [], []
with torch.no_grad(): for inputs, targets in data_loader: inputs, targets = inputs.to(device), targets.to(device) outputs = model(inputs) predictions = torch.argmax(outputs, dim=-1).view(-1) # Flatten predicted indices all_preds.extend(predictions.cpu().numpy()) all_targets.extend(targets.view(-1).cpu().numpy()) # Ensure targets are also flattened # Calculate precision, recall, and F1 score after ensuring all_preds and all_targets are correctly aligned. accuracy = accuracy_score(all_targets, all_preds) precision = precision_score(all_targets, all_preds, average='macro', zero_division=0) recall = recall_score(all_targets, all_preds, average='macro', zero_division=0) f1 = f1_score(all_targets, all_preds, average='macro', zero_division=0) print(f"Accuracy: {accuracy:.4f}") print(f"Precision: {precision:.4f}") print(f"Recall: {recall:.4f}") print(f"F1 Score: {f1:.4f}") return accuracy ,precision, recall, f1 - Assistant
- User
give me an implementation of Ray Tune or Optuna
- Assistant
- User
this is what i gor: Number of finished trials: 100 Best trial: {'n_estimators': 52, 'max_depth': 5, 'min_samples_split': 0.3617578791126733, 'min_samples_leaf': 7} Best trial accuracy: 1.0
- Assistant
Great! Your Optuna optimization process has successfully completed 100 trials and found a combination of hyperparameters for the
RandomForestClassifierthat achieved perfect accuracy (1.0) on your test split of the Iris dataset. The best hyperparameters found are:n_estimators: 52max_depth: 5min_samples_split: approximately 0.362
- User
how can i benifit from this and use it on my own dataset instead to find the best hyperparameters for my model
- Assistant
- User
my dataset is in jsonl format and contains two fields: question and answer, and i have already made a json tokenizer that maps strings from dataset to numbers, implement that into the optuna code please
- Assistant
- User
implement this dataset loading class instead that i used in the training code: class QAJsonlDataset(Dataset): def init(self, path, seq_len, tokenizer_path): # Load the trained tokenizer self.tokenizer = Tokenizer.from_file(tokenizer_path)
self.seq_len = seq_len self.pairs = self.load_data(path) # Using BPE, so no need for manual vocab or idx2token. # Tokenization will now happen using self.tokenizer. self.tokenized_pairs = [(self.tokenize(q), self.tokenize(a)) for q, a in self.pairs] def load_data(self, path): pairs = [] with open(path, "r", encoding="utf-8") as f: for line in f: data = json.loads(line.strip()) question, answer = data.get("input", ""), data.get("output", "") pairs.append((question, answer)) # Store questions and answers as raw strings return pairs def tokenize(self, text): # Tokenizing using the BPE tokenizer encoded = self.tokenizer.encode(text) tokens = encoded.ids # Padding/truncation if len(tokens) < self.seq_len: # Padding tokens += [self.tokenizer.token_to_id("<pad>")] * (self.seq_len - len(tokens)) else: # Truncation tokens = tokens[:self.seq_len - 1] + [self.tokenizer.token_to_id("<eos>")] return tokens def __len__(self): return len(self.tokenized_pairs) def __getitem__(self, idx): tokenized_question, tokenized_answer = self.tokenized_pairs[idx] return torch.tensor(tokenized_question, dtype=torch.long), torch.tensor(tokenized_answer, dtype=torch.long) - Assistant
- User
- Assistant
- User
- Assistant
- User
- Assistant
- User
- Assistant
- User
- Assistant
Based on the detailed code you've provided and considering the previous discussion about possible shapes mismatch, the next step is to analyze the new error once you run this updated script. Given your modifications and a refined approach, if you still encounter a shape mismatch error similar to the previous it will likely boil down to one of the following issues within your architecture:
- User
this is the new error that i got: Traceback (most recent call last): File "c:\Users\L14\Documents\Projets\Easy-MoE\Easy-MoE\Optuna.py", line 267, in study.optimize(objective, n_trials=20) File "C:\Users\L14\AppData\Local\Programs\Python\Python310\lib\site-packages\optuna\study\study.py", line 442, in optimize _optimize( File "C:\Users\L14\AppData\Local\Programs\Python\Python310\lib\site-packages\optuna\study_optimize.py", line 66, in _optimize _optimize_sequential( File "C:\Users\L14\AppData\Local\Programs\Python\Python310\lib\site-packages\optuna\study_optimize.py", line 163, in _optimize_sequential frozen_trial = _run_trial(study, func, catch) File "C:\Users\L14\AppData\Local\Programs\Python\Python310\lib\site-packages\optuna\study_optimize.py", line 251, in _run_trial raise func_err File "C:\Users\L14\AppData\Local\Programs\Python\Python310\lib\site-packages\optuna\study_optimize.py", line 200, in _run_trial value_or_values = func(trial) File "c:\Users\L14\Documents\Projets\Easy-MoE\Easy-MoE\Optuna.py", line 261, in objective train_loss = train(model, criterion, optimizer, num_epochs, data_loader, label_smoothing=0.1) File "c:\Users\L14\Documents\Projets\Easy-MoE\Easy-MoE\Optuna.py", line 161, in train predictions = model(inputs) File "C:\Users\L14\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\nn\modules\module.py", line 1501, in _call_impl return forward_call(*args, **kwargs) File "c:\Users\L14\Documents\Projets\Easy-MoE\Easy-MoE\Optuna.py", line 145, in forward embedded = self.dropout(self.embedding(x)) File "C:\Users\L14\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\nn\modules\module.py", line 1501, in _call_impl return forward_call(*args, **kwargs) File "C:\Users\L14\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\nn\modules\sparse.py", line 162, in forward return F.embedding( File "C:\Users\L14\AppData\Local\Programs\Python\Python310\lib\site-packages\torch\nn\functional.py", line 2210, in embedding return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) RuntimeError: Expected tensor for argument #1 'indices' to have one of the following scalar types: Long, Int; but got torch.FloatTensor instead (while checking arguments for embedding)
- Assistant
- User
- Assistant