Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

popraw ten kod: import os from pathlib import Path import torch from google.colab import…

  1. User

    popraw ten kod: import os from pathlib import Path import torch from google.colab import drive from datasets import load_dataset from transformers import T5Tokenizer, T5ForConditionalGeneration from torch.utils.data import Dataset, DataLoader from tqdm import tqdm

    Sprawdzamy, czy TPU jest dostępne

    def get_device(): if "COLAB_GPU" in os.environ: return "cuda" elif "COLAB_TPU_ADDR" in os.environ: return "tpu" else: return "cpu"

    Klasa do tworzenia Dataset zamiast IterableDataset

    class CustomDataset(Dataset): def init(self, dataset): self.dataset = dataset

    def __len__(self):
        return len(self.dataset)
    
    def __getitem__(self, idx):
        example = self.dataset[idx]
        return {
            "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: sample_text = "To jest przykładowy tekst do testowego forward pass." inputs = tokenizer(sample_text, return_tensors="pt").to(device)

        attention_mask = inputs["attention_mask"].bool()
        input_ids = inputs["input_ids"].long()
    
        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}")
    

    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')
    
    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)
    
    # Ustawienie urządzenia
    device = get_device()
    print(f"Używanie urządzenia: {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}")
        return
    
    # Ładowanie zbioru danych
    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}")
        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
    
    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).to(device)
            attention_mask = (input_ids != tokenizer.pad_token_id).long().to(device)
    
            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}")
            return None
    
    # Przetwarzanie danych
    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.")
    
    train_pytorch_dataset = CustomDataset(processed_data)
    
    # Funkcja do zbierania danych
    def collate_fn(batch):
        input_ids = torch.stack([item["input_ids"] for item in batch]).long()
        attention_mask = torch.stack([item["attention_mask"] for item in batch]).bool()
        labels = torch.stack([item["labels"] for item in batch]).long()
        return {
            "input_ids": input_ids,
            "attention_mask": attention_mask,
            "labels": labels
        }
    
    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")
        )
        model.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}")
        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}"):
            optimizer.zero_grad()
            try:
                input_ids = batch["input_ids"].to(device)
                attention_mask = batch["attention_mask"].to(device)
                labels = batch["labels"].to(device)
    
                outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
                loss = outputs.loss
                loss.backward()
                optimizer.step()
    
                epoch_loss += loss.item()
                batch_count += 1
            except Exception as e:
                print(f"Błąd podczas treningu: {e}")
    
        avg_loss = epoch_loss / batch_count if batch_count > 0 else float('inf')
        print(f"Średni loss w epoce {epoch + 1}: {avg_loss}")
    
    print("Trening zakończony.")
    

    Montowanie Google Drive

    drive.mount('/content/drive')

    Ścieżka do zapisu modelu w Google Drive

    model_save_path = "/content/drive/MyDrive/model_save_directory"

    Tworzenie katalogu, jeśli nie istnieje

    os.makedirs(model_save_path, exist_ok=True)

    Zapisz model i tokenizer

    model.save_pretrained(model_save_path) tokenizer.save_pretrained(model_save_path)

    print(f"Model i tokenizer zapisane w: {model_save_path}")

    if name == "main": main(

  2. Assistant

    Poprawiłem Twój kod, uwzględniając następujące zmiany:

    1. Ścieżki plików: Zmieniłem base_path na odpowiedni dla Google Colab (/content), ponieważ ścieżka E:/aiv2 jest specyficzna dla systemu Windows i nie będzie działać w Colabie.

    2. Montowanie Google Drive: Przeniosłem kod montowania Google Drive oraz zapisywania modelu i tokenizera do funkcji main(), aby mieć dostęp do zmiennych model i tokenizer.

    3. Urządzenie: Zaktualizowałem funkcję get_device() do sprawdzania dostępności GPU za pomocą torch.cuda.is_available() oraz TPU w Colabie.

    4. Poprawki w funkcji preprocess_function: Upewniłem się, że dane są prawidłowo przetwarzane i że zwracane tensory mają odpowiednie kształty.

    5. Zapis modelu i tokenizera: Dodałem kod zapisu modelu i tokenizera na końcu funkcji main(), aby upewnić się, że zmienne są dostępne.

    6. Obsługa wyjątków: Poprawiłem obsługę wyjątków i komunikaty błędów, aby były bardziej informacyjne.

    Poniżej znajduje się poprawiony kod:

    import os
    from pathlib import Path
    import torch
    from google.colab import drive
    from datasets import load_dataset
    from transformers import T5Tokenizer, T5ForConditionalGeneration
    from torch.utils.data import Dataset, DataLoader
    from tqdm import tqdm
    
    # Sprawdzamy, czy GPU lub TPU jest dostępne
    def get_device():
        if torch.cuda.is_available():
            return "cuda"
        elif 'COLAB_TPU_ADDR' in os.environ:
            return "tpu"
        else:
            return "cpu"
    
    # Klasa do tworzenia Dataset
    class CustomDataset(Dataset):
        def __init__(self, dataset):
            self.dataset = dataset
    
        def __len__(self):
            return len(self.dataset)
    
        def __getitem__(self, idx):
            example = self.dataset[idx]
            return {
                "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:
            sample_text = "To jest przykładowy tekst do testowego forward pass."
            inputs = tokenizer(sample_text, return_tensors="pt").to(device)
    
            attention_mask = inputs["attention_mask"]
            input_ids = inputs["input_ids"]
    
            with torch.no_grad():
                outputs = model(
                    input_ids=input_ids,
                    attention_mask=attention_mask,
                    labels=input_ids
                )
            print("Forward pass zakończony sukcesem.")
        except Exception as e:
            print(f"Błąd podczas testowego forward pass: {e}")
    
    # Główna funkcja programu
    def main():
        # Montowanie Google Drive
        drive.mount('/content/drive')
    
        # Ścieżka do zapisu modelu w Google Drive
        model_save_path = "/content/drive/MyDrive/model_save_directory"
    
        # Tworzenie katalogu, jeśli nie istnieje
        os.makedirs(model_save_path, exist_ok=True)
    
        # Ustawienie ścieżek cache
        base_path = Path("/content")
        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')
    
        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)
    
        # Ustawienie urządzenia
        device = get_device()
        print(f"Używanie urządzenia: {device}")
    
        # Ładowanie tokenizera
        try:
            tokenizer = T5Tokenizer.from_pretrained(
                't5-small',
                cache_dir=str(cache_path / "huggingface"),
                use_fast=True
            )
            print("Tokenizer załadowany pomyślnie.")
        except Exception as e:
            print(f"Błąd podczas ładowania tokenizera: {e}")
            return
    
        # Ładowanie zbioru danych
        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}")
            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
    
        if text_column is None:
            print("Nie znaleziono odpowiedniej kolumny tekstowej w zbiorze danych.")
            return
    
        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)
                attention_mask = model_inputs["attention_mask"].squeeze(0)
    
                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}")
                return None
    
        # Przetwarzanie danych
        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.")
    
        if len(processed_data) == 0:
            print("Brak przetworzonych danych do treningu.")
            return
    
        train_pytorch_dataset = CustomDataset(processed_data)
    
        # Funkcja do zbierania danych
        def collate_fn(batch):
            input_ids = torch.stack([item["input_ids"] for item in batch])
            attention_mask = torch.stack([item["attention_mask"] for item in batch])
            labels = torch.stack([item["labels"] for item in batch])
            return {
                "input_ids": input_ids,
                "attention_mask": attention_mask,
                "labels": labels
            }
    
        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")
            )
            model.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}")
            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}"):
                optimizer.zero_grad()
                try:
                    input_ids = batch["input_ids"].to(device)
                    attention_mask = batch["attention_mask"].to(device)
                    labels = batch["labels"].to(device)
    
                    outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
                    loss = outputs.loss
                    loss.backward()
                    optimizer.step()
    
                    epoch_loss += loss.item()
                    batch_count += 1
                except Exception as e:
                    print(f"Błąd podczas treningu: {e}")
    
            avg_loss = epoch_loss / batch_count if batch_count > 0 else float('inf')
            print(f"Średni loss w epoce {epoch + 1}: {avg_loss}")
    
        print("Trening zakończony.")
    
        # Zapisz model i tokenizer
        try:
            model.save_pretrained(model_save_path)
            tokenizer.save_pretrained(model_save_path)
            print(f"Model i tokenizer zapisane w: {model_save_path}")
        except Exception as e:
            print(f"Błąd podczas zapisywania modelu i tokenizera: {e}")
    
    if __name__ == "__main__":
        main()
    

    Wyjaśnienie wprowadzonych zmian:

    • Montowanie Google Drive i zapisywanie modelu: Przeniosłem kod montowania Google Drive oraz zapisywania modelu i tokenizera do funkcji main(), aby mieć dostęp do zmiennych model i tokenizer. Upewniłem się również, że ścieżka model_save_path jest poprawnie zdefiniowana.

    • Poprawki ścieżek: Zmieniłem base_path na /content, co jest odpowiednie dla środowiska Google Colab. Wszystkie katalogi cache są tworzone wewnątrz /content/models.

    • Funkcja get_device(): Zaktualizowałem funkcję, aby używała torch.cuda.is_available() do sprawdzania dostępności GPU oraz sprawdzała obecność TPU w Colab.

    • Funkcja preprocess_function: Poprawiłem sposób, w jaki są przetwarzane dane wejściowe i maska uwagi. Upewniłem się, że tensory są odpowiednio wyciskane (squeeze(0)), aby mieć prawidłowe wymiary.

    • Obsługa pustego zbioru danych: Dodałem sprawdzenie, czy przetworzone dane są niepuste przed kontynuowaniem procesu treningu.

    • Zapisywanie modelu i tokenizera: Dodałem blok try-except podczas zapisywania modelu i tokenizera, aby obsłużyć ewentualne błędy.

    • Poprawki w funkcji collate_fn: Upewniłem się, że tensory są odpowiednio stackowane bez konieczności jawnego rzutowania typów danych.

    Upewnij się, że uruchamiasz ten kod w środowisku Google Colab i że masz zainstalowane wszystkie potrzebne biblioteki.