Add comprehensive MDC files for various technologies and frameworks

Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including:
- AI/ML libraries (PyTorch, TensorFlow, scikit-learn)
- Backend frameworks (Django, FastAPI, Express, Spring Boot)
- Frontend frameworks (React, Vue, Angular)
- Cloud platforms (AWS, Azure, GCP)
- Development tools (Docker, Kubernetes, Terraform)
- State management libraries
- UI component libraries
- Web technologies and APIs

Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
sanjeed5
2025-02-27 16:58:58 +05:30
parent 676f3376bf
commit 5068ef1d22
88 changed files with 20037 additions and 0 deletions
+174
View File
@@ -0,0 +1,174 @@
---
description: This rule provides comprehensive best practices for developing with the modal library, covering code organization, performance, security, testing, and common pitfalls. It aims to guide developers towards writing maintainable, efficient, and secure modal applications.
globs: **/*.py
---
- **Purpose and Clarity:** Ensure the modal's title clearly states its purpose and use concise headers. Use power words to grab attention (e.g., 'New,' 'Exclusive,' 'You').
- **User Control:** Modals should only be used for critical information and should not disrupt the user experience. Provide visible options for users to close the modal easily. Use a dark overlay to guide attention.
- **Accessibility:** Test modals with assistive technologies to ensure they are accessible to all users. Limit the use of system-initiated modals to avoid user frustration. Adhere to WAI-ARIA guidelines for modal implementation.
## 1. Code Organization and Structure
- **Directory Structure:**
- `modal.py`: Core module containing the `modal` class and related functions.
- `modal/`: A directory containing submodules:
- `modal/config.py`: Configuration settings for modal deployment and runtime.
- `modal/stub.py`: Definition and handling of modal stubs for local development.
- `modal/secret.py`: Secure handling of secrets required by modal applications.
- `modal/image.py`: Image definition and building processes.
- `modal/volume.py`: Management of persistent volumes for data storage.
- **File Naming Conventions:** Use descriptive names (e.g., `modal_api.py`, `modal_utils.py`). Follow PEP 8 guidelines for Python file names.
- **Module Organization:** Group related functionality into modules (e.g., `modal.network`, `modal.security`).
- **Component Architecture:**
- Decouple components for reusability and testability.
- Use dependency injection to manage dependencies between components.
- **Code Splitting Strategies:** Break down large files into smaller, more manageable modules. Consider lazy-loading modules that are not immediately needed.
## 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Singleton:** Use sparingly, typically for global configuration objects.
- **Factory:** For creating modal objects with complex initialization logic.
- **Observer:** For handling events triggered by modal state changes.
- **Recommended Approaches:**
- Use context managers (`with` statement) for resource management.
- Employ decorators for adding functionality (e.g., caching, logging).
- **Anti-patterns:**
- Avoid global state, as it can lead to unpredictable behavior.
- Avoid deeply nested code, which is hard to read and maintain.
- Avoid hardcoding configuration values.
- **State Management:**
- Use immutable data structures for state to prevent unintended modifications.
- Implement clear state transition logic.
- Consider using a state management library like `modal.aio_libs.AioState` for complex scenarios.
- **Error Handling:**
- Use try-except blocks to handle potential exceptions.
- Log errors with sufficient context for debugging.
- Raise custom exceptions for specific error conditions.
## 3. Performance Considerations
- **Optimization Techniques:**
- Use caching to avoid redundant computations.
- Profile code to identify performance bottlenecks.
- Optimize database queries.
- **Memory Management:**
- Use generators to process large datasets in chunks.
- Explicitly release resources when they are no longer needed.
- Be mindful of memory leaks.
- **Rendering Optimization:** (If applicable for UI elements within modal).
- Minimize DOM manipulations.
- Use efficient rendering algorithms.
- **Bundle Size Optimization:**
- Remove unused code.
- Use code minification and compression.
- Leverage tree shaking to eliminate dead code.
- **Lazy Loading:** Defer loading non-critical resources until they are needed.
## 4. Security Best Practices
- **Common Vulnerabilities:**
- Input validation vulnerabilities (e.g., SQL injection, cross-site scripting).
- Authentication and authorization vulnerabilities.
- Data breaches due to insecure storage.
- **Input Validation:**
- Validate all user inputs before processing them.
- Use input sanitization techniques to prevent injection attacks.
- **Authentication and Authorization:**
- Use strong authentication mechanisms (e.g., multi-factor authentication).
- Implement role-based access control.
- Securely store and manage user credentials using `modal.Secret`.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use secure communication protocols (e.g., HTTPS).
- Comply with relevant data privacy regulations (e.g., GDPR, CCPA).
- **Secure API Communication:**
- Use API keys or tokens for authentication.
- Rate limit API requests to prevent abuse.
- Implement proper error handling to avoid leaking sensitive information.
## 5. Testing Approaches
- **Unit Testing:**
- Test individual functions and classes in isolation.
- Use mocking to isolate dependencies.
- Write test cases for different scenarios, including edge cases.
- **Integration Testing:**
- Test the interaction between different components.
- Verify that data flows correctly between modules.
- **End-to-end Testing:**
- Test the entire application workflow.
- Simulate user interactions to verify functionality.
- **Test Organization:**
- Organize tests into separate directories based on the module being tested.
- Use descriptive test names.
- **Mocking and Stubbing:**
- Use mocking to replace external dependencies with controlled substitutes.
- Use stubs to provide predefined responses for external calls.
## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- Incorrectly handling asynchronous operations.
- Not properly closing resources (e.g., files, network connections).
- Ignoring error conditions.
- **Edge Cases:**
- Handling empty or invalid input data.
- Dealing with network timeouts and failures.
- Ensuring compatibility with different operating systems and environments.
- **Version-Specific Issues:**
- Be aware of breaking changes in newer versions of the library.
- Check the release notes for known issues and workarounds.
- **Compatibility Concerns:**
- Ensure compatibility with different Python versions.
- Consider cross-platform compatibility.
- **Debugging Strategies:**
- Use debuggers to step through code and inspect variables.
- Use logging to track program execution and identify errors.
- Use assertions to verify expected conditions.
## 7. Tooling and Environment
- **Recommended Development Tools:**
- IDE: VS Code, PyCharm.
- Debugger: pdb, ipdb.
- Profiler: cProfile.
- **Build Configuration:**
- Use a build system like `setuptools` or `poetry` to manage dependencies and create distributable packages.
- **Linting and Formatting:**
- Use linters (e.g., pylint, flake8) to enforce coding style guidelines.
- Use formatters (e.g., black, autopep8) to automatically format code.
- **Deployment Best Practices:**
- Use containerization (e.g., Docker) to create consistent and reproducible environments.
- Use infrastructure-as-code (e.g., Terraform, CloudFormation) to automate infrastructure provisioning.
- **CI/CD Integration:**
- Use CI/CD pipelines to automatically build, test, and deploy code changes.
- Integrate linters and formatters into the CI/CD pipeline.
## 8. modal Specific Best Practices
- **Efficient Use of Images:**
- Use pre-built base images whenever possible to reduce build times.
- Leverage caching mechanisms in `modal.Image` to avoid rebuilding unchanged images.
- **Data Serialization:**
- Be aware of the data serialization overhead when passing data between modal functions.
- Use efficient serialization formats like `pickle` or `protobuf` for large datasets.
- **Secret Management:**
- Use `modal.Secret` to securely manage sensitive information like API keys and passwords.
- Avoid hardcoding secrets in your code.
- **Concurrency and Parallelism:**
- Utilize `modal.method.call` and `modal.Queue` for concurrent and parallel processing.
- Understand the limitations of Python's Global Interpreter Lock (GIL) when writing multi-threaded code.
- **Resource Limits:**
- Be aware of resource limits (CPU, memory, disk space) imposed by the modal platform.
- Optimize your code to stay within these limits.
- **Monitoring and Logging:**
- Implement monitoring and logging to track the performance of your modal applications.
- Use tools like Prometheus and Grafana for visualization.
- **Cold Starts:**
- Be aware of cold start times when invoking modal functions for the first time.
- Optimize your code to reduce cold start times.
- **Version Control and Rollbacks:**
- Always use version control (e.g., Git) to track changes to your code.
- Implement rollback mechanisms to quickly revert to previous versions in case of errors.
By following these best practices, developers can build robust, scalable, and secure modal applications.
+165
View File
@@ -0,0 +1,165 @@
---
description: Enforces CUDA coding standards, performance optimizations, and best practices to ensure efficient and maintainable GPU-accelerated code. This rule provides guidance on code organization, memory management, error handling, and more.
globs: **/*.cu
---
- # CUDA Best Practices Guide
This document outlines best practices for CUDA development, focusing on code organization, performance optimization, and common pitfalls. It is based on NVIDIA's CUDA C++ Best Practices Guide and expands on it with more detailed recommendations.
- ## 1. Code Organization and Structure
- ### 1.1 Directory Structure
- Organize your CUDA project with a clear directory structure. A common structure includes:
project_root/
├── src/
│ ├── kernels/ # CUDA kernel source files (.cu)
│ ├── host/ # Host-side code (.cpp, .h)
│ ├── common/ # Shared utility code (.h, .cpp)
│ └── include/ # Header files
├── build/ # Build output directory
├── data/ # Input and output data
├── tests/ # Unit and integration tests
└── CMakeLists.txt # CMake build configuration
- ### 1.2 File Naming Conventions
- Use descriptive file names that clearly indicate the purpose of the file.
- Kernel files: `kernel_name.cu` (e.g., `matrix_multiply.cu`)
- Host files: `module_name.cpp`, `module_name.h` (e.g., `data_loader.cpp`, `data_loader.h`)
- Common files: `utility.h`, `error_handling.cpp`
- ### 1.3 Module Organization
- Divide your code into logical modules based on functionality.
- Use namespaces to avoid naming conflicts and improve code organization.
- Encapsulate CUDA kernel launches within well-defined functions or classes.
- ### 1.4 Component Architecture
- Design your application with a modular component architecture to facilitate code reuse and maintainability.
- Decouple host-side code from CUDA kernels as much as possible.
- Use abstraction layers to hide CUDA-specific details from higher-level components.
- ### 1.5 Code Splitting Strategies
- Split large CUDA kernels into smaller, more manageable functions.
- Use separate files for different kernels or related functionalities.
- Consider using template metaprogramming to generate specialized kernels at compile time.
- ## 2. Common Patterns and Anti-patterns
- ### 2.1 Design Patterns Specific to CUDA
- **CUDA Stream Pattern:** Use CUDA streams to overlap data transfers and kernel execution.
- **Memory Pooling Pattern:** Implement memory pools to reduce the overhead of frequent memory allocations and deallocations.
- **Tiling Pattern:** Divide large data structures into smaller tiles to improve data locality and cache utilization.
- **Reduction Pattern:** Use parallel reduction algorithms to efficiently compute aggregate values.
- ### 2.2 Recommended Approaches for Common Tasks
- **Error Handling:** Use the CUDA error handling API to check for errors after each CUDA function call.
- **Memory Allocation:** Use `cudaMalloc`, `cudaFree`, and related functions for memory allocation on the device.
- **Data Transfer:** Use `cudaMemcpy` to transfer data between host and device memory.
- **Kernel Launch:** Use the `<<<gridDim, blockDim, sharedMem>>>` syntax to launch CUDA kernels.
- ### 2.3 Anti-patterns and Code Smells to Avoid
- **Synchronous Memory Transfers:** Avoid blocking memory transfers that stall the GPU.
- **Excessive Global Memory Access:** Minimize global memory access by using shared memory and registers.
- **Thread Divergence:** Avoid conditional branches that cause threads within a warp to execute different code paths.
- **Uncoalesced Memory Access:** Ensure that threads access memory in a coalesced manner to maximize memory bandwidth.
- **CPU-GPU Synchronization Bottlenecks:** Minimize the number of synchronization points between the CPU and GPU.
- ### 2.4 State Management Best Practices
- Encapsulate CUDA context and device management within a dedicated class or module.
- Avoid global state variables that can lead to unexpected behavior and concurrency issues.
- Use RAII (Resource Acquisition Is Initialization) to ensure that CUDA resources are properly released.
- ### 2.5 Error Handling Patterns
- Check the return value of every CUDA function call and handle errors appropriately.
- Use `cudaGetLastError` to retrieve the last error that occurred on the device.
- Implement custom error handling routines for specific error conditions.
- Log error messages with file name, line number, and a descriptive error message.
- ## 3. Performance Considerations
- ### 3.1 Optimization Techniques
- **Kernel Fusion:** Combine multiple kernels into a single kernel to reduce kernel launch overhead and data transfers.
- **Loop Unrolling:** Unroll loops to improve instruction-level parallelism.
- **Instruction Scheduling:** Optimize instruction scheduling to reduce pipeline stalls.
- **Constant Memory Usage:** Store frequently accessed read-only data in constant memory.
- **Texture Memory Usage:** Utilize texture memory for spatially coherent data access patterns.
- ### 3.2 Memory Management
- **Minimize Data Transfers:** Reduce the amount of data transferred between host and device.
- **Asynchronous Data Transfers:** Use asynchronous memory transfers with CUDA streams to overlap computation and communication.
- **Zero-Copy Memory:** Use zero-copy memory to directly access host memory from the GPU (use with caution due to performance implications).
- **Pinned Memory (Page-Locked Memory):** Use pinned memory for efficient asynchronous data transfers.
- ### 3.3 CUDA Profiler
- Use the NVIDIA Nsight Systems and Nsight Compute profilers to identify performance bottlenecks.
- ## 4. Security Best Practices
- ### 4.1 Common Vulnerabilities and How to Prevent Them
- **Buffer Overflows:** Carefully validate input sizes to prevent buffer overflows in CUDA kernels.
- **Integer Overflows:** Check for potential integer overflows in calculations involving data sizes and indices.
- **Race Conditions:** Protect shared data with appropriate synchronization mechanisms (e.g., atomic operations, mutexes) to prevent race conditions.
- **Injection Attacks:** Sanitize input data to prevent injection attacks that could execute arbitrary code on the GPU.
- ### 4.2 Input Validation
- Validate all input data received by CUDA kernels to ensure that it is within the expected range and format.
- Check for invalid or malicious input that could lead to security vulnerabilities.
- ### 4.3 Data Protection Strategies
- Encrypt sensitive data stored on the GPU to protect it from unauthorized access.
- Use secure communication channels to transfer data between host and device.
- ## 5. Testing Approaches
- ### 5.1 Unit Testing Strategies
- Write unit tests to verify the correctness of individual CUDA kernels and host-side functions.
- Use a testing framework like Google Test or Catch2 to automate the testing process.
- Mock CUDA runtime functions to isolate kernels during testing.
- Use a separate compilation approach to test individual kernel functions.
- ### 5.2 Integration Testing
- Perform integration tests to verify the interaction between different components of the CUDA application.
- Test data transfers between host and device, kernel launches, and error handling.
- ### 5.3 Test Organization
- Organize your tests into a logical directory structure.
- Use descriptive test names that clearly indicate the purpose of each test.
- Group related tests together into test suites.
- ### 5.4 Mocking and Stubbing
- Use mocking and stubbing techniques to isolate components during testing and simulate different scenarios.
- Mock CUDA runtime functions to control the behavior of the GPU during testing.
- ## 6. Common Pitfalls and Gotchas
- ### 6.1 Frequent Mistakes Developers Make
- **Ignoring CUDA Error Codes:** Always check the return values of CUDA functions to ensure that they succeed.
- **Incorrect Grid and Block Dimensions:** Choose appropriate grid and block dimensions for your kernels.
- **Shared Memory Bank Conflicts:** Avoid shared memory bank conflicts to maximize memory bandwidth.
- **Thread Divergence:** Minimize thread divergence within warps to improve performance.
- **Uncoalesced Memory Access:** Ensure that threads access memory in a coalesced manner.
- ### 6.2 Version-Specific Issues
- Be aware of compatibility issues between different CUDA versions.
- Use conditional compilation to handle version-specific code.
- ### 6.3 Debugging Strategies
- Use the NVIDIA Nsight Systems and Nsight Compute debuggers to debug CUDA code.
- Insert print statements to track the execution flow and variable values.
- Use the `cudaDeviceSynchronize` function to force the GPU to complete all operations before proceeding.
- ## 7. Tooling and Environment
- ### 7.1 Recommended Development Tools
- **CUDA Toolkit:** Install the latest version of the CUDA Toolkit from NVIDIA's website.
- **NVIDIA Nsight Systems and Nsight Compute:** Use the Nsight profilers to analyze and optimize CUDA code.
- **CMake:** Use CMake to manage the build process.
- **Integrated Development Environment (IDE):** Use an IDE such as Visual Studio or Eclipse with CUDA support.
- ### 7.2 Build Configuration
- Use CMake to generate build files for your target platform.
- Configure the CUDA compiler (nvcc) with appropriate optimization flags.
- ### 7.3 Linting and Formatting
- Use a linter such as clang-tidy to enforce coding standards and identify potential errors.
- Use a code formatter such as clang-format to ensure consistent code formatting.
+342
View File
@@ -0,0 +1,342 @@
---
description: This rule provides guidelines for best practices when working with the Hugging Face Transformers library, covering code organization, performance, testing, security, and common pitfalls. It emphasizes community standards and maintainability.
globs: **/*.py
---
# Hugging Face Transformers Library Best Practices
This document outlines best practices and coding standards for using the Hugging Face Transformers library. It covers various aspects, including code organization, performance, testing, security, and common pitfalls.
## Philosophy: Embrace the Single Model File Policy
- **Single Model File Policy:** Prioritize having all the code for a model's forward pass within a single file. While it might seem to contradict the DRY (Don't Repeat Yourself) principle, this improves readability and accessibility, especially for newcomers. This makes it easier to understand the entire model architecture without navigating through multiple files.
## 1. Code Organization and Structure
### 1.1 Directory Structure
While the Transformers library promotes the single model file policy, good project-level organization is still crucial. A typical project structure might look like this:
my_project/
├── data/
│ ├── raw/
│ ├── processed/
│ └── ...
├── models/
│ ├── modeling_bert.py # Example: BERT model definition
│ ├── ...
├── scripts/
│ ├── train.py
│ ├── evaluate.py
│ ├── preprocess.py
│ └── ...
├── utils/
│ ├── data_utils.py
│ ├── model_utils.py
│ └── ...
├── tests/
│ ├── test_models.py
│ ├── test_data_utils.py
│ └── ...
├── notebooks/ # optional
│ ├── exploration.ipynb
│ └── ...
├── requirements.txt
├── pyproject.toml
└── README.md
- **`data/`:** Stores raw and processed datasets.
- **`models/`:** Contains model definitions (adhering to the single model file policy).
- **`scripts/`:** Holds training, evaluation, and preprocessing scripts.
- **`utils/`:** Includes utility functions for data handling, model management, etc.
- **`tests/`:** Contains unit, integration, and end-to-end tests.
- **`notebooks/`:** (Optional) Jupyter notebooks for experimentation.
### 1.2 File Naming Conventions
- Use descriptive and consistent file names.
- For model files, follow the naming convention `modeling_<model_name>.py` (e.g., `modeling_bert.py`).
- For utility files, use `*_utils.py` (e.g., `data_utils.py`).
- Use lowercase letters and underscores for file names (snake_case).
### 1.3 Module Organization
- Keep modules focused and avoid creating overly large modules. Each module should have a clear responsibility.
- Import necessary modules within functions or classes to improve readability and avoid unnecessary dependencies at the module level.
- Use relative imports within the project structure (e.g., `from . import data_utils`) to avoid conflicts and improve portability.
### 1.4 Component Architecture
- Design models as modular components. While adhering to the single model file policy, the internal structure of the model can be highly modular. Use classes to encapsulate different parts of the model (e.g., embedding layer, attention mechanism, feedforward network).
- Each component should have a well-defined interface.
- Leverage inheritance when appropriate to share common functionality between similar components.
### 1.5 Code Splitting Strategies
- For extremely large models, consider splitting the model definition into multiple files, but maintain a clear entry point that encapsulates the entire model. A primary file should import and orchestrate the other components.
- Consider splitting preprocessing and postprocessing logic into separate modules to improve readability and maintainability.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to Hugging Face
- **Configuration-Driven Design:** Use `PretrainedConfig` objects to define model parameters. This allows for easy configuration and sharing of model architectures.
- **Tokenizers and Pipelines:** Leverage the built-in tokenizers and pipelines for efficient text processing. Understand how to customize them for specific tasks.
- **Model Cards:** Create comprehensive model cards that document the model's architecture, training data, evaluation metrics, and intended use cases. This is crucial for reproducibility and transparency.
### 2.2 Recommended Approaches for Common Tasks
- **Loading Pre-trained Models:** Use `AutoModel` and `AutoTokenizer` classes to automatically load the appropriate model and tokenizer based on the model name.
python
from transformers import AutoModelForSequenceClassification, AutoTokenizer
model_name = "bert-base-uncased"
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
- **Fine-tuning Models:** Use the `Trainer` class for efficient fine-tuning. Customize the training loop when necessary for advanced control.
python
from transformers import Trainer, TrainingArguments
training_args = TrainingArguments(
output_dir="./results",
evaluation_strategy="epoch",
num_train_epochs=3
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=eval_dataset
)
trainer.train()
- **Inference:** Use pipelines for simple inference tasks or write custom inference loops for more control.
python
from transformers import pipeline
classifier = pipeline("sentiment-analysis")
result = classifier("This is a great movie!")
### 2.3 Anti-patterns and Code Smells to Avoid
- **Ignoring `model_max_length`:** When initializing tokenizers and models, be mindful of the `model_max_length` parameter. Ensure that input sequences are properly truncated or padded to avoid errors or performance issues.
- **Hardcoding Paths:** Avoid hardcoding file paths. Use relative paths or environment variables to make the code more portable.
- **Lack of Documentation:** Write clear and concise documentation for all functions, classes, and modules. This is especially important given the single model file policy, as comprehensive inline documentation becomes critical.
- **Over-Complicating Model Definitions:** Keep model definitions as simple as possible while still meeting the requirements. Avoid unnecessary complexity.
- **Ignoring Warnings:** Pay attention to warnings raised by the Transformers library. They often indicate potential issues.
### 2.4 State Management Best Practices
- Avoid global variables. Encapsulate state within classes or functions.
- Use immutable data structures when possible to prevent accidental modifications.
- Manage model weights carefully. Load and save weights using the `state_dict` method.
python
# Save model weights
torch.save(model.state_dict(), "model.pth")
# Load model weights
model.load_state_dict(torch.load("model.pth"))
### 2.5 Error Handling Patterns
- Use `try...except` blocks to handle potential exceptions, such as file not found errors or invalid input data.
- Provide informative error messages to help users understand the cause of the error.
- Use logging to record errors and debug information.
python
import logging
logging.basicConfig(level=logging.INFO)
try:
model = AutoModelForSequenceClassification.from_pretrained("invalid-model")
except OSError as e:
logging.error(f"Failed to load model: {e}")
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Mixed Precision Training:** Use mixed precision training (e.g., using `torch.cuda.amp` in PyTorch) to reduce memory usage and improve training speed.
- **Gradient Accumulation:** Use gradient accumulation to simulate larger batch sizes when memory is limited.
- **Quantization:** Quantize models to reduce their size and improve inference speed.
- **ONNX Runtime:** Convert models to ONNX format and use the ONNX Runtime for faster inference.
### 3.2 Memory Management
- Delete unused variables and tensors to free up memory.
- Use `torch.no_grad()` during inference to disable gradient calculations and reduce memory usage.
- Consider using techniques like gradient checkpointing to reduce memory usage during training, especially for very large models.
### 3.3 Rendering Optimization (If Applicable)
- If the application involves rendering model outputs (e.g., text generation), optimize the rendering process to minimize latency and improve user experience.
- Use efficient text rendering libraries.
- Cache rendered outputs when possible.
### 3.4 Bundle Size Optimization (If Applicable)
- If the application is deployed as a web application or mobile app, optimize the bundle size to reduce download times.
- Use code splitting to load only the necessary code for each feature.
- Use minification and compression to reduce the size of JavaScript and CSS files.
### 3.5 Lazy Loading Strategies
- Load models and data lazily to reduce startup time and memory usage.
- Use generators to process large datasets in chunks.
- Only load the parts of the model that are needed for the current task.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and How to Prevent Them
- **Prompt Injection:** Be aware of prompt injection attacks, where malicious users craft inputs that can manipulate the model's behavior. Implement input validation and sanitization techniques to mitigate this risk.
- **Data Poisoning:** Protect against data poisoning attacks by carefully vetting training data sources.
- **Model Stealing:** Implement measures to protect model weights from being stolen. Consider using encryption or access controls.
### 4.2 Input Validation
- Validate all inputs to ensure that they are within the expected range and format.
- Sanitize inputs to remove potentially harmful characters or code.
- Use regular expressions to enforce input constraints.
### 4.3 Authentication and Authorization Patterns
- Implement authentication to verify the identity of users.
- Use authorization to control access to resources based on user roles.
- Store credentials securely using encryption and hashing.
### 4.4 Data Protection Strategies
- Encrypt sensitive data at rest and in transit.
- Use access controls to restrict access to data.
- Anonymize or pseudonymize data to protect user privacy.
### 4.5 Secure API Communication
- Use HTTPS to encrypt communication between the client and the server.
- Use API keys or tokens to authenticate requests.
- Implement rate limiting to prevent abuse.
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
- Write unit tests for all individual functions, classes, and modules.
- Use a testing framework like `pytest` or `unittest`.
- Test edge cases and boundary conditions.
### 5.2 Integration Testing
- Write integration tests to verify the interaction between different components of the system.
- Test the flow of data through the system.
- Use mocks and stubs to isolate components during testing.
### 5.3 End-to-end Testing
- Write end-to-end tests to verify the entire system from end to end.
- Simulate user interactions to test the system's functionality.
- Use a testing framework like `Selenium` or `Cypress` for web applications.
### 5.4 Test Organization
- Organize tests into separate files or directories based on the component being tested.
- Use descriptive names for test functions and classes.
- Keep tests concise and focused.
### 5.5 Mocking and Stubbing
- Use mocks and stubs to isolate components during testing.
- Mock external dependencies, such as API calls or database connections.
- Use a mocking library like `unittest.mock` or `pytest-mock`.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes Developers Make
- **Incorrect Tokenization:** Using the wrong tokenizer or not properly handling special tokens can lead to inaccurate results.
- **Oversized Inputs:** Forgetting to truncate or pad input sequences to the model's maximum length can cause errors or performance issues.
- **Incorrect Device Placement:** Running models on the CPU when a GPU is available can significantly slow down training and inference.
- **Ignoring Data Preprocessing:** Failing to properly preprocess data (e.g., cleaning, normalizing) can negatively impact model performance.
### 6.2 Edge Cases to be Aware Of
- **Rare Words:** Handle rare or out-of-vocabulary words gracefully.
- **Long Sequences:** Models may struggle with extremely long sequences.
- **Adversarial Examples:** Models can be fooled by adversarial examples.
### 6.3 Version-Specific Issues
- Be aware of breaking changes in new versions of the Transformers library.
- Check the release notes for details on any changes that may affect your code.
- Use version pinning in `requirements.txt` or `pyproject.toml` to ensure that your code runs with the correct version of the library.
### 6.4 Compatibility Concerns
- Ensure that your code is compatible with the target hardware and software environment.
- Test your code on different platforms and configurations.
- Use conditional imports to handle different dependencies.
### 6.5 Debugging Strategies
- Use logging to track the flow of execution and identify errors.
- Use a debugger to step through the code and inspect variables.
- Use print statements to output intermediate values.
- Use a profiler to identify performance bottlenecks.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **IDE:** Visual Studio Code, PyCharm
- **Version Control:** Git
- **Package Manager:** pip, conda, uv
- **Testing Framework:** pytest
- **Linting:** pylint, flake8
- **Formatting:** black, autopep8
### 7.2 Build Configuration
- Use `requirements.txt` or `pyproject.toml` to manage dependencies.
- Use a build system like `Make` or `Poetry` to automate the build process.
- Create a virtual environment for each project to isolate dependencies.
### 7.3 Linting and Formatting
- Use a linter to enforce code style guidelines.
- Use a formatter to automatically format code.
- Configure the linter and formatter to run automatically on save.
### 7.4 Deployment Best Practices
- Containerize your application using Docker.
- Use a cloud platform like AWS, Azure, or GCP to deploy your application.
- Use a deployment tool like Kubernetes to manage your application.
### 7.5 CI/CD Integration
- Use a CI/CD pipeline to automate the testing and deployment process.
- Use a CI/CD tool like Jenkins, GitHub Actions, or GitLab CI.
- Run tests automatically on every commit.
- Deploy the application automatically when tests pass.
## Additional Recommendations
- **Utilize NVIDIA RTX GPUs:** Leverage RTX GPUs for enhanced performance due to their high-speed VRAM and dedicated AI accelerators. This is especially important for larger models and higher batch sizes.
- **Token Management:** Understand how to manage tokens effectively to optimize performance, as performance is often measured in tokens per second.
- **Batch API:** Consider using the OpenAI Batch API for cost efficiency and higher rate limits, especially when immediate responses are not required.
By following these best practices, you can write more maintainable, efficient, and secure code when working with the Hugging Face Transformers library.
+310
View File
@@ -0,0 +1,310 @@
---
description: This rule provides best practices for developing LangChain applications, covering code organization, performance, security, testing, and common pitfalls. It aims to improve code quality, maintainability, and overall project success.
globs: **/*.py
---
# LangChain Development Best Practices
This document outlines the best practices for developing LangChain applications to ensure code quality, maintainability, performance, security, and overall project success. These guidelines cover various aspects of development, from code organization to testing and deployment.
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
Adopt a clear and consistent directory structure to improve code discoverability and maintainability. A recommended structure is:
project_root/
├── data/ # Raw data, processed data, and datasets
├── src/ # Source code directory
│ ├── components/ # Reusable LangChain components (e.g., custom chains, tools)
│ ├── chains/ # Definitions of LangChain chains
│ ├── agents/ # Agent implementations
│ ├── memory/ # Memory implementations
│ ├── utils/ # Utility functions and modules
│ ├── models/ # Custom model definitions or wrappers
│ ├── callbacks/ # Custom callback handlers
│ ├── vectorstores/ # Vectorstore configurations and connections
│ ├── document_loaders/ # Custom document loaders
│ ├── prompts/ # Prompt templates and management
│ ├── config/ # Configuration files
│ └── main.py # Entry point of the application
├── tests/ # Unit and integration tests
├── notebooks/ # Jupyter notebooks for experimentation and documentation
├── docs/ # Project documentation
├── requirements.txt # Project dependencies
├── pyproject.toml # Project metadata and build configuration
└── README.md # Project README file
### 1.2 File Naming Conventions
Use descriptive and consistent file names:
- `module_name.py`: For general modules.
- `component_name.py`: For LangChain components (e.g., `custom_chain.py`).
- `test_module_name.py`: For test files.
- Use lowercase and underscores for file names (snake_case).
### 1.3 Module Organization
Organize code into logical modules based on functionality. Each module should have a clear purpose and minimal dependencies.
- **Cohesion**: Modules should have high cohesion, meaning their elements are closely related.
- **Coupling**: Modules should have low coupling, meaning they are independent of each other as much as possible.
### 1.4 Component Architecture
Design LangChain applications using a component-based architecture. Components should be reusable, testable, and well-defined.
- **Chains**: Define chains as reusable components that encapsulate specific workflows.
- **Agents**: Implement agents as modular entities that interact with the environment using tools.
- **Memory**: Manage conversation history and state using memory components.
- **Tools**: Create tools as independent units that perform specific actions.
- **Callbacks**: Utilize callbacks for logging, monitoring, and custom event handling.
### 1.5 Code Splitting Strategies
Split large files into smaller, manageable chunks to improve readability and maintainability.
- **Function-level splitting**: Break down large functions into smaller, single-purpose functions.
- **Class-level splitting**: Divide large classes into smaller, more focused classes.
- **Module-level splitting**: Separate modules based on functionality to reduce complexity.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to LangChain
- **Chain of Responsibility**: Implement chains of operations where each component handles a specific task, passing the result to the next component.
- **Strategy Pattern**: Use strategy patterns to encapsulate different algorithms or behaviors within interchangeable strategy objects.
- **Template Method**: Define the skeleton of an algorithm in a base class, allowing subclasses to override specific steps without changing the algorithm's structure.
- **Factory Pattern**: Use factory patterns to create instances of LangChain components dynamically, based on configuration or runtime conditions.
### 2.2 Recommended Approaches for Common Tasks
- **Prompt Engineering**: Use prompt templates to manage and reuse prompts. Optimize prompts for clarity, context, and desired output.
- **Data Loading**: Implement custom data loaders to handle various data sources and formats. Use text splitters to chunk large documents into smaller pieces for retrieval.
- **Vector Storage**: Use vector stores to store and retrieve embeddings efficiently. Choose the appropriate vector store based on performance, scalability, and cost.
- **Agent Design**: Design agents with clear objectives, tools, and decision-making logic. Use observation logs to track agent actions and outcomes.
- **Memory Management**: Implement memory components to maintain conversation history and context. Use sliding window or summarization techniques to manage long conversations.
### 2.3 Anti-patterns and Code Smells to Avoid
- **God Classes**: Avoid creating large classes that handle too many responsibilities.
- **Long Methods**: Avoid creating long methods that are difficult to understand and maintain.
- **Duplicated Code**: Avoid duplicating code across multiple modules. Extract common code into reusable functions or components.
- **Magic Numbers**: Avoid using magic numbers or hardcoded values. Define constants or configuration variables instead.
- **Tight Coupling**: Avoid creating tight coupling between modules. Use interfaces and dependency injection to promote loose coupling.
### 2.4 State Management Best Practices
- **Stateless Components**: Design components to be stateless whenever possible. This improves testability and scalability.
- **Centralized State**: Manage application state in a centralized location (e.g., a state management class or library).
- **Immutable State**: Use immutable data structures to prevent unintended side effects and improve predictability.
- **Explicit State Transitions**: Define explicit state transitions to make state changes clear and traceable.
### 2.5 Error Handling Patterns
- **Try-Except Blocks**: Use try-except blocks to handle exceptions and prevent application crashes.
- **Logging**: Log errors and exceptions to facilitate debugging and monitoring.
- **Custom Exceptions**: Define custom exceptions to represent specific error conditions.
- **Retry Logic**: Implement retry logic for transient errors (e.g., network timeouts).
- **Fallback Strategies**: Implement fallback strategies for critical operations to ensure application resilience.
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Caching**: Implement caching mechanisms to store frequently accessed data and results.
- **Batch Processing**: Process data in batches to reduce overhead and improve throughput.
- **Asynchronous Operations**: Use asynchronous operations to perform non-blocking I/O and improve responsiveness.
- **Connection Pooling**: Use connection pooling to reuse database connections and reduce latency.
- **Data Compression**: Compress data to reduce storage space and network bandwidth.
- **Vectorstore Optimization**: Use efficient vectorstore implementations (e.g., FAISS, Annoy) and optimize indexing parameters for fast retrieval.
### 3.2 Memory Management
- **Object Pooling**: Use object pooling to reuse objects and reduce memory allocation overhead.
- **Garbage Collection**: Monitor garbage collection performance and tune parameters to minimize pauses.
- **Memory Profiling**: Use memory profiling tools to identify memory leaks and optimize memory usage.
- **Lazy Loading**: Load data on demand to reduce initial memory footprint.
- **Chunking Large Documents**: Process large documents in smaller chunks to avoid memory overflow.
### 3.3 Rendering Optimization (if applicable for UI components)
- **Virtualization**: Use virtualization techniques to render large lists efficiently.
- **Debouncing and Throttling**: Use debouncing and throttling to reduce the frequency of UI updates.
- **Memoization**: Use memoization to cache expensive rendering calculations.
### 3.4 Bundle Size Optimization (if applicable for web apps)
- **Code Splitting**: Split code into smaller chunks to reduce initial load time.
- **Tree Shaking**: Use tree shaking to remove unused code from bundles.
- **Minification and Compression**: Minify and compress code to reduce bundle size.
- **Lazy Loading**: Load components and modules on demand.
### 3.5 Lazy Loading Strategies
- **On-Demand Loading**: Load data or components only when they are needed.
- **Intersection Observer**: Use the Intersection Observer API to load components when they become visible in the viewport.
- **Dynamic Imports**: Use dynamic imports to load modules asynchronously.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and How to Prevent Them
- **Prompt Injection**: Prevent prompt injection by validating and sanitizing user inputs. Use prompt templates and parameterized queries to avoid direct injection of malicious code.
- **Data Exfiltration**: Prevent data exfiltration by restricting access to sensitive data and implementing data masking techniques.
- **Code Execution**: Prevent arbitrary code execution by avoiding the use of `eval()` or similar functions. Use safe alternatives for dynamic code generation.
- **Denial of Service (DoS)**: Prevent DoS attacks by implementing rate limiting, input validation, and resource quotas.
### 4.2 Input Validation
- **Whitelisting**: Validate inputs against a whitelist of allowed values or patterns.
- **Sanitization**: Sanitize inputs to remove or escape potentially harmful characters or code.
- **Type Checking**: Enforce type checking to ensure that inputs conform to expected data types.
- **Length Limits**: Enforce length limits to prevent buffer overflows or excessive memory usage.
### 4.3 Authentication and Authorization Patterns
- **Authentication**: Use strong authentication mechanisms (e.g., multi-factor authentication) to verify user identities.
- **Authorization**: Implement role-based access control (RBAC) to restrict access to resources based on user roles.
- **Least Privilege**: Grant users the minimum necessary privileges to perform their tasks.
- **Secure Storage**: Store sensitive credentials (e.g., API keys) securely using encryption or secret management tools.
### 4.4 Data Protection Strategies
- **Encryption**: Encrypt sensitive data at rest and in transit.
- **Data Masking**: Mask sensitive data to protect it from unauthorized access.
- **Data Anonymization**: Anonymize data to remove personally identifiable information (PII).
- **Access Logging**: Log all data access events to track and monitor usage.
- **Data Retention**: Define and enforce data retention policies to minimize the risk of data breaches.
### 4.5 Secure API Communication
- **HTTPS**: Use HTTPS to encrypt communication between clients and servers.
- **API Keys**: Protect API keys and other sensitive credentials.
- **Rate Limiting**: Implement rate limiting to prevent abuse and DoS attacks.
- **Input Validation**: Validate all API inputs to prevent injection attacks.
- **Output Encoding**: Encode API outputs to prevent cross-site scripting (XSS) attacks.
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
- **Test-Driven Development (TDD)**: Write unit tests before writing the code to be tested.
- **Mocking**: Use mocking to isolate components and test them independently.
- **Assertion**: Use assertions to verify that the code behaves as expected.
- **Coverage**: Aim for high code coverage to ensure that all code paths are tested.
- **Parameterized Tests**: Use parameterized tests to test multiple scenarios with different inputs.
### 5.2 Integration Testing
- **Component Integration**: Test the integration between components to ensure that they work together correctly.
- **API Integration**: Test the integration with external APIs to ensure that data is exchanged correctly.
- **Database Integration**: Test the integration with databases to ensure that data is stored and retrieved correctly.
- **End-to-End Flows**: Test end-to-end flows to ensure that the application works as a whole.
### 5.3 End-to-End Testing
- **UI Testing**: Test the user interface to ensure that it is functional and user-friendly.
- **Functional Testing**: Test the functional requirements of the application to ensure that it meets the specifications.
- **Performance Testing**: Test the performance of the application to ensure that it is responsive and scalable.
- **Security Testing**: Test the security of the application to identify and mitigate vulnerabilities.
- **Accessibility Testing**: Test the accessibility of the application to ensure that it is usable by people with disabilities.
### 5.4 Test Organization
- **Test Suites**: Organize tests into test suites based on functionality or component.
- **Test Naming**: Use descriptive test names to make it clear what each test is testing.
- **Test Data**: Use realistic test data to simulate real-world scenarios.
- **Test Environment**: Set up a dedicated test environment to isolate tests from production data.
### 5.5 Mocking and Stubbing
- **Mocking**: Use mocking to replace external dependencies with controlled substitutes.
- **Stubbing**: Use stubbing to provide predefined responses to external dependencies.
- **Dependency Injection**: Use dependency injection to make it easier to mock and stub dependencies.
- **Mocking Frameworks**: Use mocking frameworks (e.g., `unittest.mock`) to simplify the mocking process.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes Developers Make
- **Hardcoding API Keys**: Storing API keys directly in the code instead of using environment variables.
- **Ignoring Rate Limits**: Failing to handle API rate limits, leading to errors and service disruptions.
- **Lack of Input Validation**: Not validating user inputs, making the application vulnerable to prompt injection attacks.
- **Insufficient Error Handling**: Not handling errors properly, leading to application crashes and data loss.
- **Over-Reliance on Default Settings**: Using default settings without considering their impact on performance and security.
### 6.2 Edge Cases to Be Aware Of
- **Empty Inputs**: Handling empty inputs gracefully to prevent errors.
- **Long Inputs**: Handling long inputs efficiently to avoid performance issues.
- **Special Characters**: Handling special characters correctly to prevent injection attacks.
- **Unicode Support**: Ensuring proper Unicode support to handle different languages and character sets.
- **Network Errors**: Handling network errors gracefully to ensure application resilience.
### 6.3 Version-Specific Issues
- **API Changes**: Being aware of API changes in different LangChain versions and updating code accordingly.
- **Compatibility**: Ensuring compatibility between different LangChain components and versions.
- **Deprecated Features**: Avoiding the use of deprecated features and migrating to their replacements.
### 6.4 Compatibility Concerns
- **Python Versions**: Ensuring compatibility with different Python versions.
- **Operating Systems**: Ensuring compatibility with different operating systems (e.g., Windows, macOS, Linux).
- **Dependency Conflicts**: Resolving dependency conflicts between different libraries.
### 6.5 Debugging Strategies
- **Logging**: Use logging to track the execution flow and identify errors.
- **Debugging Tools**: Use debugging tools (e.g., `pdb`) to step through code and inspect variables.
- **Print Statements**: Use print statements strategically to output debugging information.
- **Error Messages**: Pay attention to error messages and stack traces to understand the root cause of errors.
- **Remote Debugging**: Use remote debugging to debug applications running on remote servers.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **IDE**: Use a powerful IDE (e.g., VS Code, PyCharm) with support for Python and LangChain.
- **Linters**: Use linters (e.g., `flake8`, `pylint`) to enforce code style and identify potential errors.
- **Formatters**: Use formatters (e.g., `black`, `autopep8`) to automatically format code according to PEP 8 standards.
- **Debuggers**: Use debuggers (e.g., `pdb`, `ipdb`) to step through code and inspect variables.
- **Version Control**: Use Git for version control and collaboration.
### 7.2 Build Configuration
- **`pyproject.toml`**: Use `pyproject.toml` file to manage project metadata, dependencies, and build configuration.
- **`requirements.txt`**: Generate and update the `requirements.txt` file to specify project dependencies.
- **Virtual Environments**: Use virtual environments (`venv`, `conda`) to isolate project dependencies.
### 7.3 Linting and Formatting
- **Linting**: Configure linters to enforce code style and identify potential errors automatically.
- **Formatting**: Configure formatters to automatically format code according to PEP 8 standards.
- **Pre-commit Hooks**: Use pre-commit hooks to run linters and formatters before committing code.
### 7.4 Deployment Best Practices
- **Containerization**: Use containerization (e.g., Docker) to package the application and its dependencies.
- **Orchestration**: Use orchestration tools (e.g., Kubernetes) to manage and scale the application.
- **Infrastructure as Code (IaC)**: Use IaC tools (e.g., Terraform, CloudFormation) to provision and manage infrastructure.
- **Monitoring**: Implement monitoring and logging to track application performance and identify issues.
- **Continuous Deployment**: Implement continuous deployment to automate the deployment process.
### 7.5 CI/CD Integration
- **Continuous Integration (CI)**: Use CI tools (e.g., GitHub Actions, GitLab CI, Jenkins) to automatically build, test, and analyze code.
- **Continuous Delivery (CD)**: Use CD tools to automatically deploy code to staging or production environments.
- **Automated Testing**: Integrate automated testing into the CI/CD pipeline to ensure code quality.
- **Rollback Strategies**: Implement rollback strategies to quickly revert to previous versions in case of deployment failures.
By following these best practices, developers can build robust, scalable, and maintainable LangChain applications that meet the needs of their users and stakeholders.
This comprehensive guide is designed to help developers create high-quality LangChain applications by adhering to industry-standard coding practices and principles.
@file best_practices_python.mdc
@file best_practices_langchain_specific.mdc
+140
View File
@@ -0,0 +1,140 @@
---
description: This rule outlines the best practices and coding standards for developing with the vllm library, ensuring code quality, performance, and maintainability. It covers code organization, performance considerations, security, testing, and common pitfalls.
globs: **/*.py
---
- ## General
- Adhere to the Google Python Style Guide: vllm projects should strictly follow the Google Python Style Guide for consistency and readability.
- Adhere to the Google C++ Style Guide (where applicable, especially for backend components).
- Pass all linter checks: Ensure code passes all configured linter checks (e.g., pylint, flake8) before committing.
- Always use UV when installing dependencies.
- Always use Python 3.12 or higher.
- Prefer classes over bare functions for better code organization and state management (where appropriate).
- ## Code Organization and Structure:
- **Directory Structure Best Practices:**
- `vllm/` (Root directory):
- `api/`: Contains API endpoints and related logic.
- `core/`: Core functionalities and algorithms.
- `layers/`: Custom layers for the models.
- `models/`: Model definitions and configurations.
- `sampling/`: Sampling algorithms.
- `sequence/`: Sequence management and data structures.
- `utils/`: Utility functions and helper modules.
- `tests/`: Unit and integration tests.
- `examples/`: Example usage and demonstrations.
- `docs/`: Documentation.
- Maintain clear separation of concerns.
- **File Naming Conventions:**
- Use descriptive and meaningful names for files and modules (e.g., `attention_layer.py`, `model_loader.py`).
- Follow snake_case for Python files and variables.
- **Module Organization:**
- Group related functionalities into modules.
- Use `__init__.py` files to define packages and control module imports.
- **Component Architecture:**
- Design components with clear interfaces and responsibilities.
- Favor composition over inheritance to promote flexibility and reusability.
- **Code Splitting Strategies:**
- Break down large modules into smaller, more manageable files.
- Utilize lazy loading or dynamic imports to reduce startup time.
- ## Common Patterns and Anti-patterns:
- **Design Patterns Specific to vllm:**
- **Model Abstraction:** Decouple the model implementation from the core engine.
- **Sequence Manager:** Centralized management of sequences and their states.
- **Asynchronous Execution:** Use asyncio to handle concurrent requests and I/O operations.
- **Recommended Approaches for Common Tasks:**
- **Model Loading:** Implement a robust model loading mechanism with caching and error handling.
- **Tokenization:** Use a dedicated tokenizer class to handle tokenization and detokenization.
- **Inference:** Design an efficient inference pipeline with batching and optimized tensor operations.
- **Anti-patterns and Code Smells to Avoid:**
- **God Classes:** Avoid creating large classes with too many responsibilities.
- **Code Duplication:** Refactor duplicated code into reusable functions or classes.
- **Magic Numbers:** Use named constants for configuration values.
- **State Management Best Practices:**
- Use immutable data structures to avoid unintended side effects.
- Manage state within dedicated classes or modules.
- Avoid global state where possible.
- **Error Handling Patterns:**
- Use exceptions to handle errors and unexpected conditions.
- Provide informative error messages.
- Implement retry mechanisms for transient errors.
- ## Performance Considerations:
- **Optimization Techniques:**
- **Tensor Optimization:** Use optimized tensor operations and data layouts (e.g., `torch.compile`).
- **Kernel Fusion:** Fuse multiple operations into a single kernel to reduce overhead.
- **Quantization:** Use quantization techniques to reduce model size and memory footprint.
- **Memory Management:**
- Minimize memory allocations and deallocations.
- Use memory pooling to reuse memory buffers.
- Profile memory usage to identify bottlenecks.
- **Bundle Size Optimization:**
- Remove unused dependencies.
- **Lazy Loading Strategies:**
- Use lazy loading for large modules or resources.
- Implement asynchronous loading for non-critical components.
- ## Security Best Practices:
- **Common Vulnerabilities and How to Prevent Them:**
- **Injection Attacks:** Sanitize user inputs to prevent injection attacks.
- **Denial of Service (DoS):** Implement rate limiting and resource management to protect against DoS attacks.
- **Data Breaches:** Protect sensitive data with encryption and access controls.
- **Input Validation:**
- Validate all user inputs before processing.
- Use regular expressions or schema validation to enforce input constraints.
- **Authentication and Authorization Patterns:**
- Implement authentication to verify user identities.
- Use authorization to control access to resources.
- **Data Protection Strategies:**
- Encrypt sensitive data at rest and in transit.
- Use secure storage mechanisms.
- **Secure API Communication:**
- Use HTTPS for API communication.
- Implement API authentication and authorization.
- ## Testing Approaches:
- **Unit Testing Strategies:**
- Write unit tests for individual functions and classes.
- Use mocking and stubbing to isolate units of code.
- **Integration Testing:**
- Test the interaction between different modules and components.
- **End-to-End Testing:**
- Test the entire system from end to end.
- **Test Organization:**
- Organize tests into separate directories.
- Use descriptive names for test files and functions.
- **Mocking and Stubbing:**
- Use mocking to replace external dependencies with controlled substitutes.
- Use stubbing to provide predefined responses for function calls.
- ## Common Pitfalls and Gotchas:
- **Frequent Mistakes Developers Make:**
- **Incorrect Tensor Shapes:** Ensure tensor shapes are compatible for operations.
- **Memory Leaks:** Properly release allocated memory to prevent memory leaks.
- **Synchronization Issues:** Avoid race conditions and deadlocks in concurrent code.
- **Edge Cases to be Aware Of:**
- **Handling Empty Sequences:** Handle empty sequences gracefully.
- **Dealing with Unknown Tokens:** Implement a mechanism to handle unknown tokens.
- **Version-Specific Issues:**
- Keep dependencies up-to-date and be aware of breaking changes when upgrading.
- **Compatibility Concerns:**
- Ensure compatibility with different hardware platforms (CPU, GPU).
- Consider different versions of Python and PyTorch.
- **Debugging Strategies:**
- Use logging to track program execution.
- Use a debugger to step through code and inspect variables.
- Profile performance to identify bottlenecks.
- ## Tooling and Environment:
- **Recommended Development Tools:**
- **VS Code:** A popular code editor with Python and C++ support.
- **PyCharm:** An IDE specifically designed for Python development.
- **Build Configuration:**
- Use `setup.py` or `pyproject.toml` to define project dependencies and build configurations.
- **Linting and Formatting:**
- Use pylint, flake8, and black to enforce code style.
- **Deployment Best Practices:**
- Use Docker to containerize the application.
- Deploy to a cloud platform such as AWS, Google Cloud, or Azure.
- **CI/CD Integration:**
- Use a CI/CD pipeline to automate testing and deployment.
+175
View File
@@ -0,0 +1,175 @@
---
description: This rule outlines best practices for using the pandas library in Python, covering code style, performance, data handling, and testing. It aims to promote maintainable, efficient, and robust data analysis workflows.
globs: **/*.py
---
# Pandas Best Practices
This document provides guidelines for writing high-quality pandas code, covering various aspects from code style to performance optimization.
## 1. Code Organization and Structure
- **Directory Structure:**
- Organize your project with a clear directory structure.
- Use separate directories for data, scripts, modules, tests, and documentation.
- Example:
project_root/
├── data/
│ ├── raw/
│ └── processed/
├── src/
│ ├── modules/
│ │ ├── data_cleaning.py
│ │ ├── feature_engineering.py
│ │ └── ...
│ ├── main.py
├── tests/
│ ├── unit/
│ ├── integration/
│ └── ...
├── docs/
├── notebooks/
├── requirements.txt
└── ...
- **File Naming Conventions:**
- Use descriptive and consistent file names.
- Use snake_case for Python files and variables.
- Example: `data_processing.py`, `load_data.py`
- **Module Organization:**
- Break down your code into reusable modules.
- Each module should focus on a specific task or functionality.
- Use clear and concise function and class names within modules.
- Follow the Single Responsibility Principle (SRP).
- **Component Architecture:**
- Design your pandas-based applications with a clear component architecture.
- Separate data loading, preprocessing, analysis, and visualization into distinct components.
- Use classes to encapsulate related functionality and data.
- **Code Splitting Strategies:**
- Split large pandas operations into smaller, more manageable steps.
- Use functions or methods to encapsulate these steps.
- This improves readability and makes debugging easier.
## 2. Common Patterns and Anti-patterns
- **Design Patterns Specific to Pandas:**
- **Chain of Responsibility:** Use method chaining to perform a sequence of operations on a DataFrame.
- **Strategy Pattern:** Implement different data processing strategies based on input parameters.
- **Factory Pattern:** Use factory functions to create DataFrames or Series from various sources.
- **Recommended Approaches for Common Tasks:**
- **Data Loading:** Use `pd.read_csv()`, `pd.read_excel()`, `pd.read_sql()` to load data from different sources.
- **Data Cleaning:** Use `dropna()`, `fillna()`, `replace()` to clean missing or incorrect data.
- **Data Transformation:** Use `apply()`, `map()`, `groupby()`, `pivot_table()` to transform data.
- **Data Aggregation:** Use `groupby()`, `agg()`, `transform()` to aggregate data.
- **Data Visualization:** Use `matplotlib`, `seaborn`, or `plotly` to visualize data.
- **Anti-patterns and Code Smells to Avoid:**
- **Iterating over DataFrames with `iterrows()` or `itertuples()`:** These are slow; prefer vectorized operations.
- **Chained Indexing:** Avoid using chained indexing (e.g., `df['A']['B']`) as it can lead to unexpected behavior. Use `.loc` or `.iloc` instead.
- **Ignoring Data Types:** Always be aware of your data types and convert them appropriately using `astype()`.
- **Writing loops to filter/process the data:** Vectorize these operations to avoid performance issues.
- **Modifying DataFrame inplace:** Creating copies is a safer approach.
- **State Management Best Practices:**
- Avoid modifying DataFrames in place unless absolutely necessary.
- Make copies of DataFrames using `.copy()` to avoid unintended side effects.
- Use functional programming principles where possible to minimize state changes.
- **Error Handling Patterns:**
- Use `try-except` blocks to handle potential errors during data loading, processing, or analysis.
- Log errors and warnings using the `logging` module.
- Raise exceptions when necessary to signal errors to the calling code.
## 3. Performance Considerations
- **Optimization Techniques:**
- **Vectorization:** Use vectorized operations instead of loops whenever possible. Pandas is optimized for vectorized operations.
- **Cython:** Consider using Cython to optimize performance-critical parts of your code.
- **Numba:** Use Numba to JIT-compile NumPy and pandas code for improved performance.
- **Dask:** Use Dask for parallel processing of large datasets that don't fit in memory.
- **Parquet or Feather:** Use Parquet or Feather file formats for efficient data storage and retrieval.
- **Categorical Data:** Use categorical data types for columns with a limited number of unique values.
- **Memory Management:**
- **Data Types:** Choose appropriate data types to minimize memory usage (e.g., `int8`, `float32` instead of `int64`, `float64`).
- **Chunking:** Load large datasets in chunks to avoid memory errors.
- **Garbage Collection:** Use `gc.collect()` to explicitly release memory.
- **Sparse Data:** Use sparse data structures for data with many missing values.
## 4. Security Best Practices
- **Common Vulnerabilities and How to Prevent Them:**
- **SQL Injection:** When reading data from SQL databases, use parameterized queries or ORM frameworks to prevent SQL injection attacks.
- **CSV Injection:** Be cautious when loading CSV files from untrusted sources, as they may contain malicious formulas that can execute arbitrary code.
- **Arbitrary Code Execution:** Avoid using `eval()` or `exec()` on data loaded from untrusted sources, as this can lead to arbitrary code execution.
- **Input Validation:**
- Validate user inputs to prevent malicious data from entering your pandas workflows.
- Use regular expressions or custom validation functions to check the format and content of inputs.
- **Data Protection Strategies:**
- Encrypt sensitive data at rest and in transit.
- Use access control mechanisms to restrict access to sensitive data.
- Anonymize or pseudonymize data when possible to protect privacy.
## 5. Testing Approaches
- **Unit Testing Strategies:**
- Write unit tests for individual functions and classes.
- Use `pytest` or `unittest` for writing and running tests.
- Test edge cases and boundary conditions.
- Use assert statements to verify the correctness of your code.
- **Integration Testing:**
- Write integration tests to verify the interaction between different modules or components.
- Test the end-to-end functionality of your pandas-based applications.
- **Test Organization:**
- Organize your tests in a separate `tests` directory.
- Use a clear naming convention for your test files and functions.
- Example: `test_data_cleaning.py`, `test_load_data()`
- **Mocking and Stubbing:**
- Use mocking and stubbing to isolate units of code during testing.
- Use the `unittest.mock` module or third-party libraries like `pytest-mock`.
## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes Developers Make:**
- **Forgetting to set the index properly:** This can lead to performance issues when joining or merging DataFrames.
- **Incorrectly handling missing data:** Be aware of how missing data is represented in your DataFrames and handle it appropriately.
- **Not understanding the difference between `.loc` and `.iloc`:** These methods are used for different types of indexing and can lead to unexpected results if used incorrectly.
- **Edge Cases to Be Aware Of:**
- **Empty DataFrames:** Handle the case where a DataFrame is empty.
- **DataFrames with duplicate indices:** Be aware of how pandas handles DataFrames with duplicate indices.
- **Debugging Strategies:**
- Use the `print()` function or the `logging` module to debug your code.
- Use a debugger to step through your code and inspect variables.
- Use the `pdb` module for interactive debugging.
## 7. Tooling and Environment
- **Recommended Development Tools:**
- **Jupyter Notebook/Lab:** For interactive data exploration and analysis.
- **VS Code with Python extension:** For code editing, debugging, and testing.
- **PyCharm:** A full-featured IDE for Python development.
- **Linting and Formatting:**
- Use `flake8` to lint your code and identify potential issues.
- Use `black` to automatically format your code according to PEP 8.
- Use `isort` to automatically sort your imports.
- Integrate these tools into your pre-commit hooks to ensure consistent code style.
- **CI/CD Integration:**
- Use CI/CD pipelines to automate the testing and deployment of your pandas-based applications.
- Integrate your CI/CD pipelines with your version control system (e.g., GitHub, GitLab, Bitbucket).
- Use Docker to containerize your applications for consistent deployment.
This comprehensive guide covers the key aspects of pandas best practices and coding standards. By following these guidelines, you can write more maintainable, efficient, and robust pandas code.
@@ -0,0 +1,381 @@
---
description: This rule provides comprehensive guidelines for PyTorch development, covering code organization, performance optimization, security, testing, and common pitfalls. It aims to ensure readable, maintainable, and efficient PyTorch code.
globs: **/*.py
---
# PyTorch Best Practices and Coding Standards
This document provides comprehensive guidelines for developing PyTorch projects, encompassing code organization, performance optimization, security, testing methodologies, and common pitfalls. Adhering to these best practices will result in more readable, maintainable, and efficient PyTorch code.
**Library Information:**
- Name: PyTorch
- Category: ai_ml
- Subcategory: machine_learning
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
A well-organized directory structure enhances code maintainability and collaboration. Here's a recommended structure for PyTorch projects:
project_root/
├── data/
│ ├── raw/
│ ├── processed/
│ └── ...
├── models/
│ ├── layers.py
│ ├── networks.py
│ ├── losses.py
│ ├── ops.py
│ └── model_name.py
├── src/
│ ├── data/
│ │ ├── datasets.py
│ │ ├── dataloaders.py
│ │ └── transforms.py
│ ├── models/
│ │ └── ... (model-related code)
│ ├── utils/
│ │ └── ... (utility functions)
│ └── visualization/
│ └── ...
├── notebooks/
│ └── ... (Jupyter notebooks for experimentation)
├── tests/
│ ├── unit/
│ ├── integration/
│ └── ...
├── scripts/
│ └── train.py
│ └── eval.py
├── configs/
│ └── ... (Configuration files, e.g., YAML)
├── README.md
├── requirements.txt
├── .gitignore
└── ...
- `data/`: Stores raw and processed datasets.
- `models/`: Contains PyTorch model definitions, layers, and custom loss functions. Separate network architectures, individual layers/blocks, and operations into different files.
- `src/`: Holds the main source code, including data loading, model definitions, utility functions, and visualization tools. It's common to split the `src/` folder further based on responsibilities.
- `notebooks/`: Jupyter notebooks for experimentation and exploration. Use notebooks for initial exploration and prototyping but transition finalized code to Python scripts.
- `tests/`: Unit, integration, and end-to-end tests.
- `scripts/`: Training, evaluation, and deployment scripts. The main training script should import model definitions.
- `configs/`: Configuration files for hyperparameter settings and other parameters.
### 1.2 File Naming Conventions
- Use descriptive and consistent file names.
- Python files: `lower_with_under.py` (e.g., `data_loader.py`, `model_utils.py`).
- Model files: `model_name.py` (e.g., `resnet.py`, `transformer.py`).
- Configuration files: `config_name.yaml` (e.g., `train_config.yaml`).
### 1.3 Module Organization
- Group related functions and classes into modules.
- Use clear and concise module names.
- Include a docstring at the beginning of each module to describe its purpose.
- Follow a consistent import style:
python
# Standard library imports
import os
import sys
# Third-party library imports
import numpy as np
import torch
import torchvision
# Local application/library imports
from src.data import data_loader
from src.models import resnet
from src.utils import helper_functions
### 1.4 Component Architecture
- **`nn.Module`:** The fundamental building block for creating neural networks in PyTorch. Always subclass `nn.Module` for defining models, layers, and custom operations.
- **`forward()` method:** Implement the forward pass of your module within the `forward()` method. PyTorch uses the `__call__` method, which executes `forward()`, to pass data through the model.
- **Separation of Concerns:** Design models as compositions of smaller, reusable modules. This promotes modularity and simplifies debugging.
Example:
python
import torch.nn as nn
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1):
super().__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
self.relu = nn.ReLU()
self.bn = nn.BatchNorm2d(out_channels)
def forward(self, x):
x = self.conv(x)
x = self.relu(x)
x = self.bn(x)
return x
class SimpleCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.conv1 = ConvBlock(3, 32)
self.conv2 = ConvBlock(32, 64)
self.pool = nn.MaxPool2d(2, 2)
self.fc = nn.Linear(64 * 8 * 8, num_classes)
def forward(self, x):
x = self.conv1(x)
x = self.pool(x)
x = self.conv2(x)
x = self.pool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
### 1.5 Code Splitting Strategies
- **Vertical Splitting (Feature-based):** Divide code based on features or functionalities (e.g., data loading, model definition, training loop). This approach aligns well with module organization.
- **Horizontal Splitting (Layer-based):** Split code based on layers or components of a neural network. This is suitable for complex models with distinct layers (e.g., encoder, decoder). The `models/` directory structure supports this.
- **Microservices (for large projects):** For very large and complex machine learning deployments, consider breaking the workload into microservices - one for training, one for inference, another for data preprocessing, etc. This can improve scalability and fault tolerance.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to PyTorch
- **`nn.Sequential`:** A container for chaining layers in a sequential manner. Suitable for simple, linear models.
- **Custom `nn.Module`:** Create custom modules for encapsulating reusable blocks of layers or operations. This promotes modularity and code reuse.
- **Hooks:** Utilize forward and backward hooks for inspecting and modifying activations and gradients during training. Useful for debugging and research.
- **DataParallel/DistributedDataParallel:** Wrap models with `DataParallel` or `DistributedDataParallel` to leverage multiple GPUs for training. `DistributedDataParallel` is generally preferred for multi-node training and offers better performance.
- **Transfer Learning:** Reuse pretrained models from `torchvision.models` as a starting point for new tasks. Fine-tune the pretrained weights or add custom layers.
### 2.2 Recommended Approaches for Common Tasks
- **Data Loading:** Use `torch.utils.data.Dataset` and `torch.utils.data.DataLoader` for efficient data loading and batching. Use custom Datasets to control data transformation.
- **Model Definition:** Define models as classes that inherit from `nn.Module`. Use the layers defined in `torch.nn` to build the model.
- **Training Loop:** Implement a structured training loop that iterates over epochs and batches. Include forward pass, loss calculation, backward pass, and optimization steps.
- **Validation:** Evaluate model performance on a validation set during training to monitor overfitting and tune hyperparameters.
- **Checkpointing:** Save model weights and optimizer state during training to resume training or load the best model.
### 2.3 Anti-patterns and Code Smells to Avoid
- **Hardcoding shapes:** Avoid hardcoding input or output shapes. Use dynamic shapes or calculate shapes based on input data.
- **Global Variables:** Minimize the use of global variables. Pass data and configurations as function arguments.
- **Magic Numbers:** Avoid using magic numbers without explanation. Define constants with descriptive names.
- **Deeply Nested Loops:** Optimize performance-critical sections of code. Consider using vectorized operations or optimized data structures to avoid nested loops where possible.
- **Ignoring Warnings:** Address all warnings. They often indicate potential problems or inefficiencies in your code. Use a debugger and logging to diagnose runtime behavior.
- **Over-commenting:** Avoid redundant comments that simply reiterate the code. Focus on explaining the *why* rather than the *what*.
- **Not using GPU when Available:** Always check if cuda is available and moves tensors and models to cuda for faster training and inference.
### 2.4 State Management Best Practices
- **Model Parameters:** Model parameters are automatically managed by PyTorch. Use `nn.Parameter` to register tensors as model parameters.
- **Buffers:** Use `nn.Buffer` to store non-trainable tensors that are part of the model state (e.g., running statistics in BatchNorm).
- **Optimizer State:** The optimizer maintains its own state, such as learning rate and momentum. Access and modify optimizer state through the `optimizer.state_dict()` and `optimizer.load_state_dict()` methods.
- **Random Seeds:** Set random seeds for reproducibility:
python
import numpy as np
import torch
def set_seed(seed):
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # if using multiple GPUs
torch.backends.cudnn.deterministic = True #Ensures that CUDA uses deterministic algorithms.
torch.backends.cudnn.benchmark = False #Prevents CUDA from benchmarking multiple convolution algorithms.
### 2.5 Error Handling Patterns
- **Specific Exception Handling:** Catch specific exceptions rather than using bare `except` clauses. This allows you to handle different error scenarios appropriately.
- **Logging:** Use the `logging` module to log errors and warnings. Include relevant information, such as timestamps, file names, and line numbers.
- **Assertion Statements:** Use `assert` statements to check for unexpected conditions. This can help catch errors early in development.
- **Custom Exceptions:** Define custom exception classes for specific error conditions in your application. This improves code readability and maintainability.
- **Graceful Degradation:** Implement mechanisms to handle errors gracefully, such as providing default values or skipping problematic data points. Avoid crashing the application.
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **GPU Utilization:** Use a GPU for training and inference. Move models and tensors to the GPU using `.to('cuda')`.
- **Batch Size:** Tune the batch size to maximize GPU utilization without running out of memory. Larger batch sizes generally lead to better performance.
- **Data Loading:** Optimize data loading by using multiple workers in the `DataLoader`. Consider using asynchronous data loading techniques.
- **Mixed Precision Training:** Use mixed precision training (`torch.cuda.amp`) to reduce memory usage and accelerate training on NVIDIA GPUs with Tensor Cores.
- **Gradient Accumulation:** Accumulate gradients over multiple batches to simulate a larger batch size when memory is limited.
- **Operator Fusion:** Utilize PyTorch's JIT compiler (`torch.jit.script` or `torch.jit.trace`) to fuse multiple operations into a single kernel, reducing overhead and improving performance.
- **Memory Usage:** When using `DataParallel`, ensure that the input data is evenly distributed across the available GPUs. Uneven data distribution can result in memory imbalances and slow down training.
### 3.2 Memory Management
- **Tensor Deletion:** Delete unnecessary tensors using `del` to free up memory.
- **`torch.no_grad()`:** Use `torch.no_grad()` during inference to disable gradient calculation and reduce memory usage.
- **In-place Operations:** Use in-place operations (e.g., `x.add_(1)`) to modify tensors directly without creating new tensors. Be cautious with in-place operations as they can sometimes cause issues with autograd.
- **Memory Profiling:** Use memory profiling tools to identify memory leaks and optimize memory usage.
- **Garbage Collection:** Explicitly call `gc.collect()` to force garbage collection. This can be useful in situations where memory is not being released promptly.
### 3.3 Rendering Optimization (if applicable)
- This section applies if PyTorch is used for rendering tasks (e.g., neural rendering).
- **Optimize Mesh Data Structures:** Use efficient mesh data structures to reduce memory usage and improve rendering performance.
- **Level of Detail (LOD):** Implement LOD techniques to reduce the complexity of rendered objects at a distance.
- **Caching:** Cache frequently accessed data to reduce rendering time.
### 3.4 Bundle Size Optimization (if applicable)
- This section applies if PyTorch models are deployed in web applications or other size-sensitive environments.
- **Model Quantization:** Quantize models to reduce their size. Use `torch.quantization` to quantize models to 8-bit integers.
- **Model Pruning:** Prune unimportant weights from models to reduce their size. Use `torch.nn.utils.prune` to prune models.
- **ONNX Export:** Convert PyTorch models to ONNX format for deployment on various platforms.
### 3.5 Lazy Loading Strategies
- **Lazy Initialization:** Defer the initialization of expensive resources until they are needed.
- **Data Streaming:** Load data in smaller chunks instead of loading the entire dataset into memory at once.
- **Just-In-Time (JIT) Compilation:** Use `torch.jit.script` or `torch.jit.trace` to compile models just before they are used. This can improve performance and reduce memory usage.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and How to Prevent Them
- **Adversarial Attacks:** Be aware of adversarial attacks that can manipulate model predictions. Implement techniques like adversarial training and input sanitization.
- **Data Poisoning:** Protect against data poisoning attacks by validating input data and using robust training techniques.
- **Model Extraction:** Prevent model extraction by limiting access to model weights and predictions.
- **Integer Overflow:** Be aware of integer overflow issues in user-provided data.
### 4.2 Input Validation
- **Data Type Validation:** Ensure that input data has the correct data type.
- **Range Validation:** Check that input values are within a valid range.
- **Format Validation:** Validate the format of input strings (e.g., URLs, email addresses).
- **Sanitization:** Sanitize input data to remove potentially malicious characters or code.
### 4.3 Authentication and Authorization Patterns
- **API Keys:** Use API keys to authenticate clients accessing your models.
- **OAuth 2.0:** Implement OAuth 2.0 for secure authorization of user access.
- **Role-Based Access Control (RBAC):** Use RBAC to restrict access to specific models or functionalities based on user roles.
### 4.4 Data Protection Strategies
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Anonymization:** Anonymize data to protect user privacy.
- **Differential Privacy:** Use differential privacy techniques to protect the privacy of training data.
- **Access Control:** Implement strict access control policies to limit access to sensitive data.
### 4.5 Secure API Communication
- **HTTPS:** Use HTTPS to encrypt communication between clients and your API.
- **TLS/SSL:** Use TLS/SSL certificates to secure your API endpoints.
- **Rate Limiting:** Implement rate limiting to prevent denial-of-service attacks.
- **Input Validation:** Always validate and sanitize input data to prevent injection attacks.
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
- **Test Individual Modules:** Write unit tests for individual modules to ensure they function correctly.
- **Test Edge Cases:** Test edge cases and boundary conditions to identify potential errors.
- **Use Assertions:** Use assertions to verify expected outcomes.
- **Test Model Outputs:** Verify that model outputs have the correct shape and data type.
### 5.2 Integration Testing
- **Test Interactions Between Modules:** Write integration tests to ensure that different modules work together correctly.
- **Test Data Pipelines:** Test the entire data pipeline, from data loading to model output.
- **Test End-to-End Functionality:** Test the entire application to ensure that it meets the requirements.
### 5.3 End-to-End Testing
- **Simulate User Interactions:** Write end-to-end tests that simulate user interactions with the application.
- **Test the Entire System:** Test the entire system, including the user interface, API, and database.
- **Verify Expected Outcomes:** Verify that the application produces the expected outcomes.
### 5.4 Test Organization
- **Separate Test Files:** Create separate test files for each module or component.
- **Use a Test Runner:** Use a test runner (e.g., `pytest`, `unittest`) to discover and run tests.
- **Follow a Consistent Naming Convention:** Follow a consistent naming convention for test files and test functions.
### 5.5 Mocking and Stubbing
- **Use Mocks to Isolate Units:** Use mocks to isolate units of code from their dependencies.
- **Use Stubs to Provide Test Data:** Use stubs to provide test data to units of code.
- **Verify Interactions with Dependencies:** Verify that units of code interact with their dependencies as expected.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes Developers Make
- **Incorrect Tensor Shapes:** Pay close attention to tensor shapes when performing operations. Use `torch.Size()` to check tensor shapes.
- **Gradient Issues:** Be mindful of gradient flow. Ensure that gradients are properly calculated and propagated through the network. Use `torch.autograd.set_detect_anomaly(True)` for debugging autograd issues.
- **Memory Leaks:** Be careful to deallocate tensors when they are no longer needed. Use memory profiling tools to identify memory leaks.
- **Data Type Mismatches:** Ensure that tensors have the correct data type (e.g., `torch.float32`, `torch.int64`).
- **Device Mismatches:** Ensure that tensors and models are on the same device (CPU or GPU).
### 6.2 Edge Cases to Be Aware Of
- **Empty Datasets:** Handle cases where datasets are empty or contain missing data.
- **Out-of-Memory Errors:** Handle out-of-memory errors gracefully by reducing batch size or using gradient accumulation.
- **Numerical Instability:** Be aware of numerical instability issues, such as vanishing or exploding gradients. Use techniques like gradient clipping and batch normalization.
### 6.3 Version-Specific Issues
- **Compatibility with Libraries:** Be aware of compatibility issues between different versions of PyTorch and other libraries.
- **API Changes:** Track API changes in PyTorch releases and update your code accordingly.
### 6.4 Compatibility Concerns
- **Hardware Compatibility:** Ensure that your code is compatible with different hardware configurations (e.g., different GPUs).
- **Operating System Compatibility:** Ensure that your code is compatible with different operating systems (e.g., Linux, Windows, macOS).
### 6.5 Debugging Strategies
- **Print Statements:** Use print statements to inspect the values of tensors and variables.
- **Debuggers:** Use a debugger (e.g., `pdb`) to step through your code and inspect the state of your application.
- **TensorBoard:** Use TensorBoard to visualize model training progress, including loss curves, metrics, and model architecture.
- **`torch.autograd.set_detect_anomaly(True)`:** A powerful tool for debugging autograd issues. It will raise an error when a NaN gradient is detected, helping you pinpoint the source of the problem.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **IDEs:** Visual Studio Code (with Python extension), PyCharm.
- **Virtual Environments:** `venv`, `conda`.
- **Debugging Tools:** `pdb`, `ipdb`.
- **Profiling Tools:** `torch.profiler`, `memory_profiler`.
### 7.2 Build Configuration
- **`requirements.txt`:** Specify project dependencies in a `requirements.txt` file. Use `pip freeze > requirements.txt` to generate the file.
Example `requirements.txt`:
torch==1.13.1
torchvision==0.14.1
numpy==1.24.1
- **`setup.py` (for libraries):** Use `setup.py` to define your library's metadata and dependencies.
### 7.3 Linting and Formatting
- **Linters:** `flake8`, `pylint`.
- **Formatters:** `black`, `autopep8`.
- **Pre-commit Hooks:** Use pre-commit hooks to automatically run linters and formatters before committing code.
### 7.4 Deployment Best Practices
- **Model Serialization:** Use `torch.save` to serialize models for deployment. Use `torch.load` to load models.
- **ONNX Export:** Convert PyTorch models to ONNX format for deployment on various platforms.
- **Serving Frameworks:** Use serving frameworks like TorchServe, FastAPI, or Flask to deploy PyTorch models as REST APIs.
### 7.5 CI/CD Integration
- **Continuous Integration (CI):** Use CI tools like Jenkins, GitHub Actions, or GitLab CI to automatically build and test your code.
- **Continuous Deployment (CD):** Use CD tools to automatically deploy your code to production environments.
- **Automated Testing:** Integrate automated testing into your CI/CD pipeline to ensure code quality and prevent regressions. Run unit, integration, and end-to-end tests.
@@ -0,0 +1,193 @@
---
description: Enforces best practices and coding standards for scikit-learn projects, promoting maintainability, performance, and security. This rule provides guidelines on code organization, common patterns, performance optimization, testing, and common pitfalls.
globs: **/*.py
---
# Scikit-learn Best Practices and Coding Standards
This document outlines best practices and coding standards for developing with scikit-learn, aiming to improve code quality, maintainability, performance, and security.
## 1. Code Organization and Structure
- **Directory Structure:**
- Organize your project into logical modules or components. A typical structure might include:
- `src/`: Source code for your project.
- `models/`: Contains the implementation of machine learning models.
- `features/`: Feature engineering and processing logic.
- `utils/`: Utility functions and helper modules.
- `data/`: Datasets used for training and testing.
- `raw/`: Original, unprocessed data.
- `processed/`: Cleaned and preprocessed data.
- `notebooks/`: Jupyter notebooks for experimentation and analysis.
- `tests/`: Unit and integration tests.
- `scripts/`: Scripts for training, evaluation, and deployment.
- `config/`: Configuration files (e.g., YAML, JSON).
- Example:
project_root/
├── src/
│ ├── models/
│ │ ├── __init__.py
│ │ ├── model_1.py
│ │ └── model_2.py
│ ├── features/
│ │ ├── __init__.py
│ │ ├── feature_engineering.py
│ │ └── feature_selection.py
│ ├── utils/
│ │ ├── __init__.py
│ │ └── helpers.py
│ ├── __init__.py
│ └── main.py
├── data/
│ ├── raw/
│ │ └── data.csv
│ └── processed/
│ └── processed_data.csv
├── notebooks/
│ └── exploratory_data_analysis.ipynb
├── tests/
│ ├── __init__.py
│ ├── test_models.py
│ └── test_features.py
├── scripts/
│ ├── train.py
│ └── evaluate.py
├── config/
│ └── config.yaml
├── README.md
└── requirements.txt
- **File Naming Conventions:**
- Use descriptive and consistent names for files and modules.
- Prefer snake_case for Python files and variables (e.g., `model_training.py`, `n_samples`).
- **Module Organization:**
- Each module should have a clear and specific purpose.
- Use `__init__.py` files to define packages and modules within directories.
- Minimize dependencies between modules to improve maintainability.
- **Component Architecture:**
- Design your application with loosely coupled components.
- Implement interfaces or abstract classes to define contracts between components.
- Use dependency injection to manage dependencies and promote testability.
- **Code Splitting Strategies:**
- Split large files into smaller, more manageable modules.
- Group related functions and classes into modules based on functionality.
- Consider splitting code based on layers (e.g., data access, business logic, presentation).
## 2. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Pipeline:** Use scikit-learn's `Pipeline` class to chain together multiple data preprocessing and modeling steps. This helps prevent data leakage and ensures consistent data transformations.
- **Model Selection:** Employ techniques like cross-validation and grid search to select the best model and hyperparameters for your data. Use `GridSearchCV` or `RandomizedSearchCV`.
- **Ensemble Methods:** Leverage ensemble methods like Random Forests, Gradient Boosting, and Voting Classifiers to improve model accuracy and robustness.
- **Custom Transformers:** Create custom transformers using `BaseEstimator` and `TransformerMixin` to encapsulate complex feature engineering logic.
- **Recommended Approaches:**
- **Data Preprocessing:** Always split your data into training and testing sets *before* any preprocessing steps.
- **Feature Scaling:** Apply appropriate feature scaling techniques (e.g., StandardScaler, MinMaxScaler) to numerical features before training models.
- **Categorical Encoding:** Use one-hot encoding or ordinal encoding for categorical features.
- **Missing Value Imputation:** Handle missing values using imputation techniques like mean, median, or k-NN imputation.
- **Model Persistence:** Save trained models to disk using `joblib` or `pickle` for later use.
- **Anti-patterns and Code Smells:**
- **Data Leakage:** Avoid data leakage by preprocessing the entire dataset before splitting into training and testing sets.
- **Overfitting:** Be cautious of overfitting by using regularization techniques and cross-validation.
- **Ignoring Data Distributions:** Always visualize and understand data distributions before applying transformations or choosing models.
- **Hardcoding Parameters:** Avoid hardcoding parameters directly in the code. Use configuration files or command-line arguments instead.
- **Ignoring Warnings:** Pay attention to scikit-learn warnings, as they often indicate potential problems with your code or data.
- **State Management:**
- Use classes to encapsulate state and behavior related to models or data processing steps.
- Avoid global variables and mutable state whenever possible.
- Use immutable data structures where appropriate to prevent unintended side effects.
- **Error Handling:**
- Use try-except blocks to handle exceptions and prevent your application from crashing.
- Log errors and warnings to a file or logging service.
- Provide informative error messages to users.
- Implement retry mechanisms for transient errors.
## 3. Performance Considerations
- **Optimization Techniques:**
- **Vectorization:** Utilize NumPy's vectorized operations to perform calculations on entire arrays instead of looping through individual elements. Use `.values` from pandas DataFrames when passing to scikit-learn.
- **Memory Optimization:** Minimize memory usage by using appropriate data types (e.g., `int8`, `float32`) and avoiding unnecessary copies of data.
- **Algorithm Selection:** Choose efficient algorithms that are well-suited for your data and task. For example, use `MiniBatchKMeans` for large datasets.
- **Parallelization:** Use scikit-learn's built-in support for parallel processing to speed up training and prediction.
- **Memory Management:**
- Use memory profiling tools to identify memory leaks and optimize memory usage.
- Release unused memory by deleting variables or using the `gc` module.
- Use data streaming techniques for large datasets that don't fit into memory.
- **Lazy Loading Strategies:**
- Load data and models only when they are needed.
- Use generators or iterators to process large datasets in chunks.
## 4. Security Best Practices
- **Common Vulnerabilities:**
- **Model Poisoning:** Protect against model poisoning attacks by validating input data and sanitizing user-provided data.
- **Adversarial Attacks:** Be aware of adversarial attacks that can manipulate model predictions. Consider using techniques like adversarial training to improve model robustness.
- **Input Validation:**
- Validate all input data to ensure it conforms to the expected format and range.
- Sanitize user-provided data to prevent injection attacks.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use access control mechanisms to restrict access to data and models.
## 5. Testing Approaches
- **Unit Testing:**
- Write unit tests for individual functions and classes.
- Use mocking to isolate components and test them in isolation.
- Assert that your code produces the expected output for different inputs.
- **Integration Testing:**
- Write integration tests to verify that different components work together correctly.
- Test the interaction between your code and external dependencies.
- **Test Organization:**
- Organize your tests into a separate directory (e.g., `tests`).
- Use descriptive names for your test files and functions.
- **Mocking and Stubbing:**
- Use mocking libraries like `unittest.mock` or `pytest-mock` to create mock objects for testing.
- Use stubs to replace complex dependencies with simpler implementations.
## 6. Common Pitfalls and Gotchas
- **Data Type Mismatches:** Ensure that the data types of your input features are compatible with the model you are using.
- **Feature Scaling Issues:** Use the correct scaling method for your features, understanding how each scaler behaves.
- **Improper Cross-Validation:** Make sure the cross-validation strategy you choose is appropriate for your dataset and model.
- **Version Compatibility:** Be aware of compatibility issues between different versions of scikit-learn and its dependencies.
## 7. Tooling and Environment
- **Recommended Development Tools:**
- **IDE:** Use an IDE like VS Code, PyCharm, or JupyterLab.
- **Version Control:** Use Git for version control.
- **Package Manager:** Use pip or Conda for managing dependencies.
- **Virtual Environments:** Create virtual environments for each project to isolate dependencies.
- **Linting and Formatting:**
- Use linters like pylint or flake8 to enforce code style and identify potential errors.
- Use formatters like black or autopep8 to automatically format your code.
- **CI/CD Integration:**
- Integrate your code with a CI/CD system like Jenkins, Travis CI, or CircleCI.
- Automatically run tests and linters on every commit.
- Deploy your application to a production environment automatically.
## General Coding Style
- Use underscores to separate words in non-class names: `n_samples` rather than `nsamples`.
- Avoid multiple statements on one line.
- Use relative imports for references inside scikit-learn (except for unit tests, which should use absolute imports).
By following these best practices, you can write cleaner, more maintainable, and more efficient scikit-learn code.
@@ -0,0 +1,185 @@
---
description: Comprehensive guide to TensorFlow best practices, covering code organization, performance, testing, and security for robust and maintainable machine learning projects.
globs: **/*.{py,tf,keras}
---
- **Code Organization and Structure:**
- **Directory Structure:**
- Structure your project into logical directories. For example:
project_root/
├── data/
│ ├── raw/
│ └── processed/
├── models/
│ ├── training/
│ └── saved_models/
├── src/
│ ├── utils/
│ ├── layers/
│ ├── models/
│ ├── training/
│ └── evaluation/
├── notebooks/ #Jupyter notebooks for experimentation
├── tests/
├── configs/
└── README.md
- **File Naming Conventions:**
- Use descriptive and consistent names. For example:
- `model_name.py`
- `data_processing.py`
- `train.py`
- `evaluate.py`
- `layer_name.py`
- **Module Organization:**
- Break down code into reusable modules and functions.
- Use `tf.Module` and Keras layers to manage variables. This enables encapsulation and avoids global variable pollution.
- Import modules using explicit relative or absolute paths, such as `from src.models import MyModel`.
- Group related functionality into modules/packages.
- **Component Architecture:**
- Employ modular design principles.
- Keras `Layers` and `Models` promote a component-based architecture. Custom layers should inherit from `tf.keras.layers.Layer`. Custom models inherit from `tf.keras.Model`.
- Use dependency injection to decouple components and facilitate testing.
- **Code Splitting Strategies:**
- Refactor code into smaller, manageable modules.
- Separate data loading, preprocessing, model definition, training, and evaluation into distinct modules.
- Implement generator functions or `tf.data.Dataset` pipelines for large datasets to avoid loading all data into memory at once.
- **Common Patterns and Anti-patterns:**
- **Design Patterns:**
- **Strategy Pattern:** Use different strategies for optimization or regularization.
- **Factory Pattern:** Create model architectures dynamically based on configuration.
- **Observer Pattern:** Monitor training progress and trigger actions based on metrics.
- **Recommended Approaches:**
- Use Keras layers and models to manage variables. Keras handles the underlying TensorFlow operations.
- Leverage `tf.data.Dataset` for efficient data loading and preprocessing.
- Use `tf.function` to compile Python functions into TensorFlow graphs for improved performance.
- **Anti-patterns and Code Smells:**
- **God Classes:** Avoid monolithic classes that perform too many tasks. Break them into smaller, more focused classes or functions.
- **Copy-Pasted Code:** Refactor duplicated code into reusable functions or modules.
- **Magic Numbers:** Use named constants instead of hardcoded values.
- **Global Variables:** Minimize the use of global variables, especially for model parameters.
- **State Management:**
- Use Keras layers and models for managing model state (weights, biases).
- Use `tf.Variable` objects for persistent state that needs to be tracked during training.
- When creating a model subclass, define trainable weights as tf.Variable objects within the `build()` method.
- Consider using `tf.saved_model` to save and load the entire model state, including the computation graph and variable values.
- **Error Handling:**
- Use `tf.debugging.assert_*` functions to check tensor values during development and debugging.
- Implement try-except blocks to handle potential exceptions, such as `tf.errors.InvalidArgumentError` or `tf.errors.OutOfRangeError`.
- Log errors and warnings using `tf.compat.v1.logging` or the standard `logging` module.
- Ensure error messages are informative and actionable.
- **Performance Considerations:**
- **Optimization Techniques:**
- Use `tf.function` to compile Python functions into TensorFlow graphs for improved performance. Use autograph (automatic graph construction).
- Optimize data input pipelines using `tf.data.Dataset.prefetch` and `tf.data.Dataset.cache`.
- Experiment with different optimizers (e.g., Adam, SGD) and learning rates.
- Adjust the default learning rate for some `tf.keras.*` optimizers.
- Use mixed precision training with `tf.keras.mixed_precision.Policy` to reduce memory usage and improve performance on GPUs.
- **Memory Management:**
- Use `tf.data.Dataset` to stream data from disk instead of loading it all into memory.
- Release unnecessary tensors using `del` to free up memory.
- Use `tf.GradientTape` to compute gradients efficiently, and avoid keeping unnecessary tensors alive within the tape.
- **GPU Utilization:**
- Ensure that TensorFlow is using the GPU by checking `tf.config.list_physical_devices('GPU')`.
- Use larger batch sizes to maximize GPU utilization.
- Profile your code using TensorFlow Profiler to identify bottlenecks and optimize GPU usage.
- **Security Best Practices:**
- **Common Vulnerabilities:**
- **Untrusted Input:** Validate all user-provided input to prevent malicious code injection or data poisoning attacks.
- **Model Poisoning:** Protect against adversarial attacks that can manipulate the training data and degrade model performance.
- **Model Inversion:** Implement techniques to protect sensitive data from being extracted from the model.
- **Input Validation:**
- Sanitize and validate all input data to prevent SQL injection, cross-site scripting (XSS), and other security vulnerabilities.
- Use `tf.io.decode_image` to decode images safely and prevent potential vulnerabilities related to malformed image files.
- Input validation for image and text data is critical.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use differential privacy techniques to protect the privacy of training data.
- Regularly audit your code and infrastructure for security vulnerabilities.
- **Secure API Communication:**
- Use HTTPS to encrypt communication between the client and the server.
- Implement authentication and authorization mechanisms to restrict access to sensitive data and functionality.
- **Testing Approaches:**
- **Unit Testing:**
- Write unit tests for individual functions and classes using `unittest` or `pytest`.
- Use `tf.test.TestCase` for testing TensorFlow-specific code.
- Mock external dependencies to isolate the code being tested.
- **Integration Testing:**
- Test the integration of different modules and components.
- Verify that the data pipeline is working correctly.
- Ensure that the model is producing accurate predictions on real-world data.
- **End-to-End Testing:**
- Test the entire workflow from data loading to model deployment.
- Use tools like Selenium or Cypress to automate end-to-end tests.
- Test for performance and scalability.
- **Test Organization:**
- Organize tests into logical directories and modules.
- Use clear and descriptive test names.
- Follow the Arrange-Act-Assert pattern for writing tests.
- **Mocking and Stubbing:**
- Use mocking frameworks like `unittest.mock` or `pytest-mock` to replace external dependencies with mock objects.
- Use stubs to provide controlled responses from external dependencies.
- **Common Pitfalls and Gotchas:**
- **Version Compatibility:**
- Be aware of version-specific issues and compatibility concerns when upgrading TensorFlow versions.
- Use `tf.compat.v1` or `tf.compat.v2` to maintain compatibility with older versions of TensorFlow.
- **Eager Execution:**
- Understand the differences between eager execution and graph execution.
- Use `tf.function` to compile functions into graphs for improved performance in production.
- **Tensor Shapes and Data Types:**
- Pay attention to tensor shapes and data types to avoid errors.
- Use `tf.debugging.assert_shapes` and `tf.debugging.assert_type` to check tensor shapes and data types during development.
- **Variable Scope:**
- Be aware of variable scope when using `tf.Variable` objects.
- Use `tf.compat.v1.get_variable` to create or reuse variables within a specific scope.
- **Tooling and Environment:**
- **Recommended Development Tools:**
- Jupyter Notebooks or Google Colab for interactive development and experimentation.
- TensorBoard for visualizing training progress and model graphs.
- TensorFlow Profiler for identifying performance bottlenecks.
- Debuggers such as the Python Debugger (pdb) for stepping through code and inspecting variables.
- **Linting and Formatting:**
- Use linters like pylint or flake8 to enforce code style guidelines.
- Use formatters like black or autopep8 to automatically format your code.
- **Deployment Best Practices:**
- Use TensorFlow Serving to deploy models in production.
- Use Docker to containerize your application and ensure consistent deployments.
- Use a platform like Vertex AI for scalable model training and deployment.
- **CI/CD Integration:**
- Integrate your code with a continuous integration/continuous delivery (CI/CD) pipeline.
- Use tools like Jenkins, Travis CI, or CircleCI to automate testing and deployment.
- **References:**
- [TensorFlow Core](https://www.tensorflow.org/guide/effective_tf2)
- [TensorFlow testing best practices](https://www.tensorflow.org/community/contribute/tests)
- [Medium - 10 tips to improve your machine learning models with tensorflow](https://medium.com/decathlondigital/10-tips-to-improve-your-machine-learning-models-with-tensorflow-ba7c724761e2)
- [Quora - What are the best practices with TensorFlow](https://www.quora.com/What-are-the-best-practices-with-TensorFlow)