Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Rindow Matlib Ffi Laravel Package

rindow/rindow-matlib-ffi

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the C Library:

    • Download the pre-built binary from releases and follow OS-specific setup instructions (Windows/Linux/macOS).
    • Ensure rindowmatlib.dll (Windows) or librindowmatlib.so (Linux/macOS) is in a system PATH or /usr/local/lib.
  2. Composer Install:

    composer require rindow/rindow-matlib-ffi rindow/rindow-math-buffer-ffi
    
  3. First Use Case: Summing an array:

    use Rindow\Matlib\FFI\MatlibFactory;
    use Rindow\Math\Buffer\FFI\BufferFactory;
    use Interop\Polite\Math\Matrix\NDArray;
    
    $factory = new MatlibFactory();
    $math = $factory->Math();
    $bufferFactory = new BufferFactory();
    
    $x = $bufferFactory->Buffer(64, NDArray::float32);
    for ($i = 0; $i < 64; $i++) $x[$i] = $i;
    
    $sum = $math->sum(64, $x, 0, 1); // Sum all elements
    

Key Dependencies

  • rindow-math-buffer-ffi: Required for memory management of numerical arrays.
  • OpenBLAS: Must be pthread-compatible (Linux/macOS). Avoid OpenMP conflicts.

Implementation Patterns

Core Workflow

  1. Buffer Initialization:

    $buffer = $bufferFactory->Buffer($size, NDArray::float64);
    
    • Use NDArray::float32/float64/int32/int64 for type safety.
  2. Matrix Operations:

    // Matrix multiplication (C = A * B)
    $math->gemm(
        $m, $n, $k,       // Dimensions
        $alpha, $A, $lda, // Matrix A (row-major, stride=lda)
        $beta,  $B, $ldb, // Matrix B (row-major, stride=ldb)
        $C,     $ldc      // Output matrix C
    );
    
    • Stride (lda, ldb, ldc): Typically rows for row-major matrices.
  3. Common Patterns:

    • Reductions: sum(), mean(), max(), min().
    • Element-wise: add(), sub(), mul(), div().
    • Linear Algebra: solve(), eig(), svd() (via gemm/getrf/getrs).
    • Machine Learning: einsum() (flexible but slow), einsum4p1() (fast for 4D+1D).
  4. Memory Management:

    • Buffers are zero-copy (FFI-backed). Avoid manual free()—use PHP’s garbage collection.
    • For large datasets, pre-allocate buffers and reuse them.

Integration with Laravel

  • Service Provider:
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Rindow\Matlib\FFI\MatlibFactory;
    
    class MatlibServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton('matlib', function () {
                return (new MatlibFactory())->Math();
            });
        }
    }
    
  • Usage in Controllers:
    use Illuminate\Support\Facades\Facade;
    
    class MatrixController extends Controller
    {
        public function multiply()
        {
            $matlib = app('matlib');
            // ... use $matlib->gemm(), etc.
        }
    }
    

Performance Tips

  • Batch Processing: Process large matrices in chunks to avoid memory spikes.
  • Threading: Use the threaded version of rindowmatlib (default) for multi-core acceleration.
  • Avoid PHP Loops: Offload computations to C via FFI (e.g., gemm instead of nested for loops).

Gotchas and Tips

Pitfalls

  1. OpenBLAS Conflicts (Linux/macOS):

    • Symptom: Crashes or slow performance.
    • Fix: Ensure libopenblas0-pthread is installed and selected via update-alternatives.
      sudo apt install libopenblas0-pthread liblapacke
      sudo update-alternatives --config libopenblas.so.0
      
    • Windows/macOS: No conflicts—use the default threaded DLL.
  2. Type Mismatches:

    • Error: FFI::memoryAccessViolation() or silent corruption.
    • Fix: Ensure buffer types (float32/float64) match function expectations. Use NDArray::* constants.
  3. Buffer Lifetime:

    • Error: "Buffer freed prematurely" or segfaults.
    • Fix: Keep PHP references to buffers alive until C operations complete. Avoid returning buffers from functions without returning them as objects/closures.
  4. macOS Quirks:

    • Issue: rindow-math-buffer-ffi may hang in CI (GitHub Actions).
    • Workaround: Use Composer-based PHPUnit setup (as per release notes).
  5. Preview Functions:

    • topk(), gathernd(): Unstable API. Use with caution or wrap in feature flags.

Debugging

  • Check Library Version:
    $version = $math->getConfig(); // Returns ["version" => "1.1.3", ...]
    
  • Validate Buffers:
    if (!$x instanceof \Rindow\Math\Buffer\FFI\Buffer) {
        throw new \RuntimeException("Invalid buffer");
    }
    
  • FFI Errors:
    • Enable FFI error reporting:
      FFI::debug(true);
      
    • Common errors:
      • FFI::memoryAccessViolation: Buffer size/type mismatch.
      • FFI::invalidArgument: Invalid strides/dimensions.

Extension Points

  1. Custom Functions:

    • Extend via FFI by loading additional C symbols:
      $ffi = FFI::cdef("
          float custom_func(float *x, int n);
      ", "rindowmatlib.dll");
      
    • Warning: Requires recompiling rindowmatlib with custom symbols.
  2. Hybrid PHP/C:

    • For complex workflows, write a C wrapper that calls rindowmatlib and expose it via FFI.
  3. Laravel Packages:

    • Package as a Laravel service (e.g., laravel-matlib) with:
      • Artisan commands for matrix operations.
      • Eloquent model observers for automated preprocessing.

Configuration

  • No Laravel Config: The package is stateless. Configure via:
    • Environment variables (e.g., MATLIB_LIBRARY_PATH).
    • Custom FFI loader:
      $ffi = FFI::load('rindowmatlib', __DIR__.'/vendor/rindow/rindow-matlib-ffi/ext/rindowmatlib.ffi');
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony