Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse files- run_distributed.bat +56 -0
- run_distributed.sh +28 -0
- run_transformers_training.py +101 -63
run_distributed.bat
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@echo off
|
2 |
+
REM ======================================================================
|
3 |
+
REM Distributed training launch script for Phi-4 training with torchrun
|
4 |
+
REM This script launches multi-GPU training on Windows systems
|
5 |
+
REM ======================================================================
|
6 |
+
|
7 |
+
REM Set the number of GPUs to use (defaults to all available)
|
8 |
+
set NUM_GPUS=%1
|
9 |
+
if "%NUM_GPUS%"=="" set NUM_GPUS=4
|
10 |
+
|
11 |
+
echo.
|
12 |
+
echo ===== Phi-4 Distributed Training =====
|
13 |
+
echo.
|
14 |
+
echo Preparing to launch training with %NUM_GPUS% GPUs...
|
15 |
+
|
16 |
+
REM Check if Python is available
|
17 |
+
where python >nul 2>&1
|
18 |
+
if %ERRORLEVEL% NEQ 0 (
|
19 |
+
echo ERROR: Python not found in PATH. Please make sure Python is installed and in your PATH.
|
20 |
+
exit /b 1
|
21 |
+
)
|
22 |
+
|
23 |
+
REM Check if PyTorch is installed by attempting to import it
|
24 |
+
python -c "import torch" >nul 2>&1
|
25 |
+
if %ERRORLEVEL% NEQ 0 (
|
26 |
+
echo ERROR: PyTorch not properly installed. Please install with:
|
27 |
+
echo pip install torch>=2.0.0
|
28 |
+
exit /b 1
|
29 |
+
)
|
30 |
+
|
31 |
+
REM Check if torch.distributed is available
|
32 |
+
python -c "import torch.distributed" >nul 2>&1
|
33 |
+
if %ERRORLEVEL% NEQ 0 (
|
34 |
+
echo ERROR: torch.distributed module not available. Please check your PyTorch installation.
|
35 |
+
exit /b 1
|
36 |
+
)
|
37 |
+
|
38 |
+
echo Environment checks passed. Starting distributed training...
|
39 |
+
echo.
|
40 |
+
|
41 |
+
REM Launch the distributed training
|
42 |
+
python -m torch.distributed.run --nproc_per_node=%NUM_GPUS% --master_port=29500 run_transformers_training.py --config transformers_config.json
|
43 |
+
|
44 |
+
REM Check exit status
|
45 |
+
if %ERRORLEVEL% EQU 0 (
|
46 |
+
echo.
|
47 |
+
echo ===== SUCCESS =====
|
48 |
+
echo Distributed training completed successfully!
|
49 |
+
) else (
|
50 |
+
echo.
|
51 |
+
echo ===== ERROR =====
|
52 |
+
echo Distributed training failed with exit code %ERRORLEVEL%
|
53 |
+
)
|
54 |
+
|
55 |
+
echo.
|
56 |
+
echo Training logs are available in the ./results directory.
|
run_distributed.sh
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
# Distributed training launch script for Phi-4 training
|
3 |
+
# This script uses torchrun to launch multi-GPU training
|
4 |
+
|
5 |
+
# Set the number of GPUs to use (defaults to all available)
|
6 |
+
NUM_GPUS=${1:-4}
|
7 |
+
|
8 |
+
# Check if torchrun is available
|
9 |
+
if ! command -v torchrun &> /dev/null; then
|
10 |
+
echo "torchrun command not found. Make sure PyTorch is installed properly."
|
11 |
+
echo "Try: pip install torch>=2.0.0"
|
12 |
+
exit 1
|
13 |
+
fi
|
14 |
+
|
15 |
+
echo "Launching distributed training with $NUM_GPUS GPUs..."
|
16 |
+
|
17 |
+
# Launch the distributed training
|
18 |
+
torchrun --nproc_per_node=$NUM_GPUS \
|
19 |
+
--master_port=29500 \
|
20 |
+
run_transformers_training.py \
|
21 |
+
--config transformers_config.json
|
22 |
+
|
23 |
+
# Check exit status
|
24 |
+
if [ $? -eq 0 ]; then
|
25 |
+
echo "Distributed training completed successfully!"
|
26 |
+
else
|
27 |
+
echo "Distributed training failed with exit code $?"
|
28 |
+
fi
|
run_transformers_training.py
CHANGED
@@ -432,7 +432,7 @@ def load_dataset_with_mapping(dataset_config):
|
|
432 |
|
433 |
except Exception as e:
|
434 |
logger.error(f"Error loading dataset: {str(e)}")
|
435 |
-
|
436 |
|
437 |
def format_phi_chat(messages, dataset_config):
|
438 |
"""Format messages according to phi-4's chat template and dataset config."""
|
@@ -502,31 +502,50 @@ class SimpleDataCollator:
|
|
502 |
|
503 |
for example in features:
|
504 |
try:
|
505 |
-
# Get ID
|
506 |
-
paper_id = example.get("article_id", example.get("id", ""))
|
507 |
|
508 |
-
#
|
509 |
-
raw_conversations = example.get("conversations"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
510 |
if not raw_conversations:
|
511 |
-
logger.warning(f"Empty conversations for example {paper_id}")
|
512 |
self.stats["skipped"] += 1
|
513 |
continue
|
514 |
|
515 |
# Extract only the 'content' field from each conversation item
|
516 |
-
# This simplifies the structure and avoids potential NoneType errors
|
517 |
try:
|
518 |
# Convert conversations to the simple format with only content
|
519 |
simplified_conversations = []
|
520 |
for item in raw_conversations:
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
525 |
elif isinstance(item, str):
|
526 |
# If it's just a string, treat it as content
|
527 |
simplified_conversations.append({"role": "user", "content": item})
|
528 |
else:
|
529 |
-
logger.warning(f"Skipping invalid conversation item: {item}")
|
530 |
|
531 |
# Skip if no valid conversations after filtering
|
532 |
if not simplified_conversations:
|
@@ -536,62 +555,66 @@ class SimpleDataCollator:
|
|
536 |
|
537 |
# Log the simplified content for debugging
|
538 |
if len(simplified_conversations) > 0:
|
539 |
-
first_content = simplified_conversations[0]
|
540 |
-
|
|
|
541 |
|
542 |
# Let tokenizer handle the simplified conversations
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
inputs = inputs[:self.max_seq_length]
|
571 |
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
# For causal language modeling, labels are the same as inputs
|
577 |
-
labels = inputs.copy()
|
578 |
-
|
579 |
-
batch["input_ids"].append(inputs)
|
580 |
-
batch["attention_mask"].append(attention_mask)
|
581 |
-
batch["labels"].append(labels)
|
582 |
|
583 |
-
|
584 |
-
|
585 |
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
594 |
self.stats["skipped"] += 1
|
|
|
|
|
595 |
except Exception as e:
|
596 |
logger.warning(f"Error processing example: {str(e)[:100]}...")
|
597 |
logger.warning(f"Problematic example ID: {example.get('id', 'unknown')}")
|
@@ -758,7 +781,22 @@ def check_dependencies():
|
|
758 |
logger.info("flash-attn found. Flash attention will be used for faster training.")
|
759 |
else:
|
760 |
logger.warning("flash-attn not found. Training will work but may be slower.")
|
761 |
-
logger.warning("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
762 |
|
763 |
# Additional optional packages that improve performance
|
764 |
if find_spec("bitsandbytes"):
|
|
|
432 |
|
433 |
except Exception as e:
|
434 |
logger.error(f"Error loading dataset: {str(e)}")
|
435 |
+
return 1
|
436 |
|
437 |
def format_phi_chat(messages, dataset_config):
|
438 |
"""Format messages according to phi-4's chat template and dataset config."""
|
|
|
502 |
|
503 |
for example in features:
|
504 |
try:
|
505 |
+
# Get ID for logging
|
506 |
+
paper_id = example.get("article_id", example.get("id", "unknown"))
|
507 |
|
508 |
+
# Safely get conversations with explicit None check
|
509 |
+
raw_conversations = example.get("conversations")
|
510 |
+
if raw_conversations is None:
|
511 |
+
logger.warning(f"Conversations is None for example {paper_id}")
|
512 |
+
self.stats["skipped"] += 1
|
513 |
+
continue
|
514 |
+
|
515 |
+
# Ensure conversations is a list
|
516 |
+
if not isinstance(raw_conversations, list):
|
517 |
+
logger.warning(f"Conversations is not a list for example {paper_id} (type: {type(raw_conversations)})")
|
518 |
+
self.stats["skipped"] += 1
|
519 |
+
continue
|
520 |
+
|
521 |
+
# Check for empty conversations list
|
522 |
if not raw_conversations:
|
523 |
+
logger.warning(f"Empty conversations list for example {paper_id}")
|
524 |
self.stats["skipped"] += 1
|
525 |
continue
|
526 |
|
527 |
# Extract only the 'content' field from each conversation item
|
|
|
528 |
try:
|
529 |
# Convert conversations to the simple format with only content
|
530 |
simplified_conversations = []
|
531 |
for item in raw_conversations:
|
532 |
+
# Skip None items
|
533 |
+
if item is None:
|
534 |
+
logger.warning(f"Skipping None conversation item in example {paper_id}")
|
535 |
+
continue
|
536 |
+
|
537 |
+
if isinstance(item, dict):
|
538 |
+
# Get content with explicit None check
|
539 |
+
content = item.get("content")
|
540 |
+
if content is not None:
|
541 |
+
simplified_conversations.append({"role": "user", "content": content})
|
542 |
+
else:
|
543 |
+
logger.warning(f"Skipping conversation item with None content in example {paper_id}")
|
544 |
elif isinstance(item, str):
|
545 |
# If it's just a string, treat it as content
|
546 |
simplified_conversations.append({"role": "user", "content": item})
|
547 |
else:
|
548 |
+
logger.warning(f"Skipping invalid conversation item type: {type(item)} in example {paper_id}")
|
549 |
|
550 |
# Skip if no valid conversations after filtering
|
551 |
if not simplified_conversations:
|
|
|
555 |
|
556 |
# Log the simplified content for debugging
|
557 |
if len(simplified_conversations) > 0:
|
558 |
+
first_content = simplified_conversations[0].get("content", "")
|
559 |
+
if first_content:
|
560 |
+
logger.debug(f"First content: {first_content[:50]}...")
|
561 |
|
562 |
# Let tokenizer handle the simplified conversations
|
563 |
+
try:
|
564 |
+
inputs = self.tokenizer.apply_chat_template(
|
565 |
+
simplified_conversations,
|
566 |
+
return_tensors=None,
|
567 |
+
add_generation_prompt=False
|
568 |
+
)
|
569 |
+
except Exception as chat_error:
|
570 |
+
# Fallback if apply_chat_template fails
|
571 |
+
logger.warning(f"Chat template application failed for example {paper_id}: {str(chat_error)}")
|
572 |
+
|
573 |
+
# Create a basic representation of just the content
|
574 |
+
conversation_text = ""
|
575 |
+
for msg in simplified_conversations:
|
576 |
+
if isinstance(msg, dict) and msg.get("content"):
|
577 |
+
conversation_text += msg["content"] + "\n\n"
|
578 |
+
|
579 |
+
if not conversation_text:
|
580 |
+
logger.warning(f"No valid content to tokenize in example {paper_id}")
|
581 |
+
self.stats["skipped"] += 1
|
582 |
+
continue
|
583 |
+
|
584 |
+
# Basic tokenization
|
585 |
+
inputs = self.tokenizer(
|
586 |
+
conversation_text,
|
587 |
+
add_special_tokens=True,
|
588 |
+
return_tensors=None
|
589 |
+
)
|
|
|
590 |
|
591 |
+
# Apply length cap if needed
|
592 |
+
if self.max_seq_length > 0 and len(inputs) > self.max_seq_length:
|
593 |
+
logger.warning(f"Example {paper_id} exceeds max_seq_length ({len(inputs)} > {self.max_seq_length})")
|
594 |
+
inputs = inputs[:self.max_seq_length]
|
|
|
|
|
|
|
|
|
|
|
|
|
595 |
|
596 |
+
# Create attention mask (1 for all tokens)
|
597 |
+
attention_mask = [1] * len(inputs)
|
598 |
|
599 |
+
if len(inputs) > 0:
|
600 |
+
# For causal language modeling, labels are the same as inputs
|
601 |
+
labels = inputs.copy()
|
602 |
+
|
603 |
+
batch["input_ids"].append(inputs)
|
604 |
+
batch["attention_mask"].append(attention_mask)
|
605 |
+
batch["labels"].append(labels)
|
606 |
+
|
607 |
+
self.stats["processed"] += 1
|
608 |
+
self.stats["total_tokens"] += len(inputs)
|
609 |
+
else:
|
610 |
+
logger.warning(f"Empty inputs after tokenization for example {paper_id}")
|
611 |
+
self.stats["skipped"] += 1
|
612 |
+
|
613 |
+
except Exception as e:
|
614 |
+
logger.warning(f"Error processing conversations in example {paper_id}: {str(e)}")
|
615 |
self.stats["skipped"] += 1
|
616 |
+
continue
|
617 |
+
|
618 |
except Exception as e:
|
619 |
logger.warning(f"Error processing example: {str(e)[:100]}...")
|
620 |
logger.warning(f"Problematic example ID: {example.get('id', 'unknown')}")
|
|
|
781 |
logger.info("flash-attn found. Flash attention will be used for faster training.")
|
782 |
else:
|
783 |
logger.warning("flash-attn not found. Training will work but may be slower.")
|
784 |
+
logger.warning("Attempting to install flash-attn automatically...")
|
785 |
+
|
786 |
+
try:
|
787 |
+
import subprocess
|
788 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "flash-attn", "--no-build-isolation"])
|
789 |
+
logger.info("Successfully installed flash-attn!")
|
790 |
+
|
791 |
+
# Try to import it now that it's installed
|
792 |
+
try:
|
793 |
+
import flash_attn
|
794 |
+
logger.info("flash-attn imported successfully after installation.")
|
795 |
+
except ImportError:
|
796 |
+
logger.warning("flash-attn installed but import failed - may require restart.")
|
797 |
+
except Exception as e:
|
798 |
+
logger.warning(f"Failed to install flash-attn: {str(e)}")
|
799 |
+
logger.warning("To manually install flash attention, run: pip install flash-attn --no-build-isolation")
|
800 |
|
801 |
# Additional optional packages that improve performance
|
802 |
if find_spec("bitsandbytes"):
|