napraw to import os from pathlib import Path import torch import traceback from datasets…
- User
napraw to import os from pathlib import Path import torch import traceback from datasets import load_dataset from transformers import T5Tokenizer, T5ForConditionalGeneration from torch.utils.data import IterableDataset, DataLoader from tqdm import tqdm
try: import torch_directml # Importowanie torch-directml except ImportError: print("Błąd: Nie znaleziono torch-directml. Używanie CPU zamiast DirectML.")
Klasa do tworzenia iterowalnego zbioru danych
class CustomIterableDataset(IterableDataset): def init(self, dataset): self.dataset = dataset
def __iter__(self): for example in self.dataset: yield { "input_ids": example["input_ids"], "attention_mask": example.get("attention_mask", torch.ones(len(example["input_ids"]), dtype=torch.bool)), "labels": example["labels"] }Funkcja do testowania forward pass
def test_forward_pass(model, tokenizer, device): try: # Przykładowe dane wejściowe sample_text = "To jest przykładowy tekst do testowego forward pass." inputs = tokenizer(sample_text, return_tensors="pt").to(device)
# Konwersja typów danych attention_mask = inputs["attention_mask"].bool() input_ids = inputs["input_ids"].long() # Generowanie decoder_input_ids decoder_input_ids = torch.cat([ torch.full((input_ids.size(0), 1), tokenizer.pad_token_id, dtype=torch.long).to(device), input_ids[:, :-1] ], dim=-1) with torch.no_grad(): outputs = model( input_ids=input_ids, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids ) print("Forward pass zakończony sukcesem.") except Exception as e: print(f"Błąd podczas testowego forward pass: {e}") traceback.print_exc()Funkcja do listowania urządzeń DirectML
def list_directml_devices(): devices = [] if 'torch_directml' in globals(): print("=== DirectML Devices ===") index = 0 while True: try: device = torch_directml.device(device_id=index) devices.append(device) print(f" Device {index}: {device}") index += 1 except Exception: break if not devices: print(" No DirectML devices found.") else: print("DirectML unavailable. Using CPU.") return devices
Prosta funkcja testowa tensorów
def simple_tensor_test(device): print("=== Simple Tensor Test ===") try: x = torch.tensor([1, 2, 3], dtype=torch.float32).to(device) y = torch.tensor([4, 5, 6], dtype=torch.float32).to(device) z = x + y print(f"Result of tensor addition: {z}") except Exception as e: print(f"Błąd podczas operacji tensorowej: {e}") traceback.print_exc() print()
Główna funkcja programu
def main(): base_path = Path("E:/aiv2") cache_path = base_path / 'models'
os.environ['HF_HOME'] = str(cache_path / 'huggingface') os.environ['HF_DATASETS_CACHE'] = str(cache_path / 'datasets_cache') os.environ['PYARROW_TMPDIR'] = str(cache_path / 'temp') os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0' cache_dirs = [cache_path / 'huggingface', cache_path / 'datasets_cache', cache_path / 'temp'] for dir_path in cache_dirs: dir_path.mkdir(parents=True, exist_ok=True) available_devices = list_directml_devices() device_id = 1 # Można ustawić na 0, jeśli chcemy używać pierwszego urządzenia if device_id < len(available_devices): device = available_devices[device_id] print(f"Używanie GPU AMD: {device}") else: device = torch.device('cpu') print(f"Używanie CPU, ponieważ DirectML device_id={device_id} nie jest dostępne.") simple_tensor_test(device) # Ładowanie tokenizera try: tokenizer = T5Tokenizer.from_pretrained( 't5-small', cache_dir=str(cache_path / "huggingface"), use_fast=True, legacy=False ) print("Tokenizer załadowany pomyślnie.") except Exception as e: print(f"Błąd podczas ładowania tokenizera: {e}") traceback.print_exc() return # Ładowanie zbioru danych (bez trybu streamingowego) try: dataset = load_dataset("neuralwork/arxiver", split='train') print("Zbiór danych załadowany pomyślnie.") except Exception as e: print(f"Błąd podczas ładowania zbioru danych: {e}") traceback.print_exc() return text_column = None try: sample_entry = dataset[0] for possible_column in ['content', 'text', 'title']: if possible_column in sample_entry: text_column = possible_column break except IndexError: print("Zbiór danych jest pusty.") return except Exception as e: print(f"Błąd podczas dostępu do wpisów zbioru danych: {e}") traceback.print_exc() return if text_column is None: raise KeyError("Nie znaleziono odpowiedniej kolumny tekstowej w zbiorze danych.") print(f"Używanie kolumny tekstowej: {text_column}") # Funkcja do przetwarzania danych def preprocess_function(example): try: inputs = example[text_column] model_inputs = tokenizer( inputs, max_length=128, truncation=True, padding="max_length", return_tensors="pt" ) input_ids = model_inputs["input_ids"].squeeze(0).long().to(device) attention_mask = model_inputs["attention_mask"].squeeze(0).bool().to(device) # Użycie bool labels = input_ids.clone() labels[labels == tokenizer.pad_token_id] = -100 return { "input_ids": input_ids, "attention_mask": attention_mask, "labels": labels } except Exception as e: print(f"Błąd w preprocess_function dla przykładu: {e}") traceback.print_exc() return None # Przetwarzanie danych try: processed_data = [] for example in tqdm(dataset, desc="Przetwarzanie danych"): processed = preprocess_function(example) if processed is not None: processed_data.append(processed) print("Przetwarzanie zbioru danych zakończone.") except Exception as e: print(f"Błąd podczas przetwarzania zbioru danych: {e}") traceback.print_exc() return train_pytorch_dataset = CustomIterableDataset(processed_data) # Funkcja do zbierania danych def collate_fn(batch): try: input_ids = torch.stack([item["input_ids"] for item in batch]).long() attention_mask = torch.stack([item["attention_mask"] for item in batch]).bool() # Użycie bool labels = torch.stack([item["labels"] for item in batch]).long() return { "input_ids": input_ids, "attention_mask": attention_mask, "labels": labels } except Exception as e: print(f"Błąd w collate_fn: {e}") traceback.print_exc() return None train_dataloader = DataLoader( train_pytorch_dataset, batch_size=4, num_workers=0, collate_fn=collate_fn ) print("DataLoader został pomyślnie utworzony.") # Ładowanie modelu try: model = T5ForConditionalGeneration.from_pretrained( 't5-small', cache_dir=str(cache_path / "huggingface") ).to(device) print(f"Model załadowany pomyślnie na {device}.") test_forward_pass(model, tokenizer, device) except Exception as e: print(f"Błąd podczas ładowania modelu: {e}") traceback.print_exc() return optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) print("Optymalizator skonfigurowany.") model.train() num_epochs = 2 for epoch in range(num_epochs): print(f"\nRozpoczynanie epoki {epoch + 1}/{num_epochs}") epoch_loss = 0 batch_count = 0 for batch in tqdm(train_dataloader, desc=f"Epoka {epoch + 1}"): if batch is None: print("Pomijanie uszkodzonego batcha.") continue optimizer.zero_grad() try: input_ids = batch["input_ids"].to(device).long() attention_mask = batch["attention_mask"].to(device).bool() # Użycie bool labels = batch["labels"].to(device).long() # Walidacja typów danych i wartości assert input_ids.dtype == torch.long, "input_ids nie jest typu torch.long" assert attention_mask.dtype == torch.bool, "attention_mask nie jest typu torch.bool" assert labels.dtype == torch.long, "labels nie jest typu torch.long" assert torch.all((attention_mask == False) | (attention_mask == True)), "attention_mask zawiera wartości inne niż False lub True" assert torch.all((labels == -100) | (labels >= 0)), "labels zawierają wartości inne niż -100 lub >=0" outputs = model( input_ids=input_ids, attention_mask=attention_mask, labels=labels ) loss = outputs.loss loss.backward() optimizer.step() except AssertionError as ae: print(f"Assertion error: {ae}") continue except Exception as e: print(f"Błąd podczas treningu: {e}") traceback.print_exc() continue epoch_loss += loss.item() batch_count += 1 avg_loss = epoch_loss / batch_count if batch_count > 0 else 0 print(f"Średni strat dla epoki {epoch + 1}: {avg_loss:.4f}") - Assistant