Tag: onnx

  • Bringing Modern ML, Columnar I/O, and RAG to Perl Data Language (PDLPorters)

    Disclaimer: The opinions stated here are my own, not those of my employer.

    In my previous post on bringing native Protocol Buffers, gRPC, and Cloud/GenAI client libraries to Perl, I noted an important split in modern AI and data engineering: remote LLM orchestration happens over RPC, while local machine learning and columnar analytics rely on in-process C, C++, and Rust tensor libraries.

    Naturally, the next question was: what about the local side of that equation?

    What started as a pair of data-interchange prototypes (PDL::IO::Arrow and PDL::IO::Protobuf) developed alongside google-auth-library-perl (#35 and #37) quickly grew once we invited review from the PDLPorters community, in particular Ed J (mohawk2 / ETJ on #pdl) and Zakariyya Mughal (ZMUGHAL). That collaboration reshaped both the architecture and the governance of the project: 16 distributions (14 PDL::* modules at 0.011 and 2 Alien::* wrappers at 0.001) have now been migrated into dedicated repositories under PDLPorters, hardened across Linux, macOS, and Windows, and submitted as 16 pull requests built directly on Perl Data Language (PDL).


    1. Eliminating the Two-Language Problem with a Clean 3-Layer PDL Architecture

    In pure Perl, a list of one million floating-point numbers is an array of one million boxed scalar structures (SVs). Historically, serializing data into and out of Perl scalars or shelling out to external Python scripts and CLI wrappers created a painful “two-language problem” for engineering teams already running Perl for systems automation, log analysis, text processing, and service orchestration.

    For nearly three decades, PDL has provided typed, contiguous C-level N-dimensional arrays (ndarrays) with vectorized broadcasting and affine slicing. What PDL lacked until now were zero-copy-friendly bridges to modern columnar file formats, deep-learning weight files, subword tokenizers, dense vector indexes, and hardware-accelerated inference runtimes.

    Guided by PDLPorters conventions and PAUSE community stewardship (relinquishing 11 deprecated prototype namespaces and transferring primary maintainership on the active namespaces to ETJ while retaining co-maintainership alongside ZMUGHAL), the stack is organized into three clean layers:

    1. Alien::* Native Runtime Layer (Alien::GGML, Alien::LibTorch): Locates system-installed C/C++ libraries via pkg-config or builds low-level HPC tensor runtimes cleanly without coupling complex native build logic to thin Perl XS wrappers.
    2. Focused Engine & Zero-Copy I/O Layer (PDL::IO::*, PDL::ML::Engine::*, PDL::ML::Vector::*, PDL::ML::Token::*): Converts directly between native memory buffers (including the Apache Arrow C Data Interface and memory-mapped .safetensors / .gguf model weights) and contiguous PDL ndarray pointers.
    3. PDL Broadcastloop & Workflow Layer (PDL::ML::Preprocess, PDL::ML::Metrics, PDL::ML::RAG): Pure-PDL feature scaling, imputation, evaluation metrics, and retrieval-augmented generation workflows that compose naturally with PDL’s broadcasting engine.

    In practice, Perl services using traditional lexical search (TF-IDF, BM25, or regex log scanning) can now add subword tokenization, local ONNX or GGML embeddings, FAISS similarity search, and analytical DuckDB SQL completely in-process over shared C pointers.


    2. Lessons Learned & Upstream XS Discipline (PDL#562 and PDL#563)

    As the modules took shape, mohawk2 opened PDLPorters/pdl#562 (“Notes on binding libraries to PDL”), where we also contributed back a consolidated PDL Binding Cookbook. Several concrete engineering idioms shaped all 16 pull requests:

    • Use PDL->new_around_datasv for runtime-typed buffers: Rather than hand-rolling pdlnew(), setdims(), allocdata(), and memcpy boilerplate in C when wrapping raw byte buffers whose element type is determined dynamically at runtime, new_around_datasv wraps the buffer cleanly and idiomatically.
    • Fail hard on missing native libraries: Every Makefile.PL replaces silent exit 0 stubs with explicit die diagnostics when required C/C++ libraries are missing, ensuring CPAN Testers, cpanm, and distro build daemons accurately distinguish missing native prerequisites from passing builds.
    • Modern Makefile.PL & C++ hygiene: Pure-XS distributions enable XSMULTI => 1, C++ bindings unconditionally use ExtUtils::CppGuess (makemaker_options()->{CCFLAGS}), quotes in PDL::Core::Dev::PDL_INCLUDE() are preserved so paths containing spaces never break, all PDL-* modules use 3-decimal versions (0.011) with META_MERGE pointing to PDLPorters/*, and every module ships a dedicated =head1 TYPES POD section documenting supported PDL types.
    • Cross-platform CI & local quality hooks: Every repository runs PDLPorters satellite GitHub Actions workflows (PDLPorters/devops/github-actions/ci-dist@master plus IRC notifications) across Linux, macOS (using dynamic brew --prefix + rpath), and native Windows (5.32), achieving 100% green CI across all 14 PDL-* distributions and Alien-GGML (with Alien-LibTorch CI underway). Local dot-git/hooks/pre-commit and pre-push scripts enforce syntax checks, Test::CPAN::Changes, Test::Pod, parallel prove -j, and Test::Kwalitee before code ever leaves a workstation.
    • Cross-distro & Perl 5.40 portability catches: Testing across Debian, Ubuntu, Rocky Linux 9, macOS, Windows, and Perl 5.40 surfaced subtle real-world traps early: for example, avoiding exporting connect by default in PDL::IO::DuckDB so it does not shadow Perl’s built-in socket connect, and isolating a C99 complex macro collision in pdl.h under strict C++17/C++20 mode into a minimal 3-file reproducer tracked upstream at PDLPorters/pdl#563.

    3. Inside the 16 PDLPorters Distributions & Pull Requests

    Architecture diagram of the PDLPorters C/C++ columnar I/O, vector search, inference, and RAG stack over Perl Data Language (PDL).
    Figure 1: Modular C/C++ columnar I/O, vector search, inference, and RAG stack over Perl Data Language (PDL).

    All 16 repositories under PDLPorters now have open pull requests spanning columnar and model-weight I/O, C/C++ ML and inference engines, dense vector search, tokenization, workflows, and Alien::* native library wrappers:

    Distribution (Version)Pull RequestNative Backend / Purpose
    PDL::IO::Arrow (0.011)PDL-IO-Arrow#1Apache Arrow C Data Interface IPC & Apache Parquet columnar read/write
    PDL::IO::DuckDB (0.011)PDL-IO-DuckDB#1In-process analytical SQL queries materialized directly into PDL ndarrays
    PDL::IO::Protobuf (0.011)PDL-IO-Protobuf#1Binary wire serialization between Protocol Buffer payloads and PDL ndarrays
    PDL::IO::Safetensors (0.011)PDL-IO-Safetensors#1Memory-mapped (mmap), zero-arbitrary-code Hugging Face .safetensors weight I/O
    PDL::IO::GGUF (0.011)PDL-IO-GGUF#1Memory-mapped quantized LLM tensor and metadata inspection for .gguf files
    PDL::ML::Engine::ONNX (0.011)PDL-ML-Engine-ONNX#1Hardware-accelerated PyTorch/JAX/TF model inference via ONNX Runtime’s C API
    PDL::ML::Engine::XGBoost (0.011)PDL-ML-Engine-XGBoost#1Gradient-boosted decision tree training and scoring via libxgboost
    PDL::ML::Engine::MLPack (0.011)PDL-ML-Engine-MLPack#1Fast C++ classical ML clustering, classification, and nearest-neighbor routines
    PDL::ML::Vector::FAISS (0.011)PDL-ML-Vector-FAISS#1High-dimensional dense vector similarity search (L2, inner product, HNSW/IVF)
    PDL::ML::Token::SentencePiece (0.011)PDL-ML-Token-SentencePiece#1C++ SentencePiece BPE and Unigram subword tokenization into integer ndarrays
    PDL::ML::Token::Tokenisers (0.011)PDL-ML-Token-Tokenisers#1Fast BPE and WordPiece subword vocabulary encoding/decoding
    PDL::ML::Preprocess (0.011)PDL-ML-Preprocess#1PDL-broadcasted feature scaling, encoding, imputation, and train/test splitting
    PDL::ML::Metrics (0.011)PDL-ML-Metrics#1Vectorized accuracy, ROC/AUC, F1, RMSE, and ranking evaluation metrics
    PDL::ML::RAG (0.011)PDL-ML-RAG#1Chunking, normalized vector storage, prompt rendering, and hybrid local/cloud RAG
    Alien::GGML (0.001)Alien-GGML#1Alien::Build package for the ggml C/C++ quantized LLM tensor library
    Alien::LibTorch (0.001)Alien-LibTorch#1Alien::Build package for C++ libtorch tensor and inference runtimes

    What It Looks Like in Practice

    Reading and writing Apache Parquet or Arrow IPC files directly as named PDL columns (which also bridges cleanly to BigQuery’s Arrow-based Google::Cloud::Bigquery::Storage::V1 API) takes a single call:

    use PDL;
    use PDL::IO::Arrow qw(rarrow warrow rparquet wparquet);
    
    # Read Parquet columnar data directly into typed PDL ndarrays
    my $cols   = rparquet('events.parquet');
    my $scores = $cols->{score};
    
    # Write named PDL columns back out to Parquet or Arrow IPC
    wparquet({ id => long([1, 2, 3]), val => double([0.5, 1.5, 2.5]) }, 'out.parquet');
    warrow({ id => long([1, 2, 3]), val => double([0.5, 1.5, 2.5]) }, 'out.arrow');

    Indexing embedding vectors in FAISS and running local ONNX Runtime inference stay equally concise:

    use PDL;
    use PDL::ML::Vector::FAISS qw(flat_l2);
    use PDL::ML::Engine::ONNX qw(load_session);
    
    # 1. k-NN similarity search in FAISS
    my $index = flat_l2(4);
    $index->add(float([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]));
    my ($distances, $indices) = $index->search(float([[0, 1, 0, 0]]), 2);
    
    # 2. Local model inspection & inference via ONNX Runtime C API
    my $sess    = load_session('model.onnx');
    my @inputs  = $sess->input_names();
    my @outputs = $sess->output_names();

    And PDL::ML::RAG ties local vector retrieval together with either a local ONNX/GGML backend or a remote gRPC call via Google::Ai::Generativelanguage::V1:

    use PDL;
    use PDL::ML::RAG qw(chunk_text render_prompt);
    
    my $rag = PDL::ML::RAG::Pipeline->new(
        embedder  => sub ($text) { ... },          # returns 1D PDL float vector
        generator => sub ($prompt, $hits) { ... }, # local ONNX/GGML or Gemini gRPC
    );
    
    $rag->ingest([
        { text => 'PDL provides fast n-dimensional arrays for Perl.', metadata => { src => 'pdl' } },
        { text => 'DuckDB runs vectorized SQL queries in-process.',   metadata => { src => 'duckdb' } },
    ]);
    
    my $res = $rag->query('How do I run SQL?', k => 1);
    print $res->{answer}, "\n";

    4. Honest Capability Assessment: Where Perl Reaches Parity (and Where Python Still Leads)

    High-level languages achieve modern ML throughput by orchestrating compiled C, C++, CUDA, and Rust engines over contiguous memory buffers. Distinguishing between analytics, tabular ML, inference, and RAG versus frontier foundation-model training clarifies what this expansion actually changes for Perl:

    Workload CategoryPerl (PDL + PDL::ML / PDL::IO)Python (NumPy / PyTorch / JAX)Assessment
    Columnar Analytics & ETLPDL::IO::Arrow, PDL::IO::DuckDB, PDL::IO::Protobufpyarrow, duckdb, polars, pandasNear Parity: Both wrap the same C++ Arrow and DuckDB engines over contiguous buffers.
    Classical & Tabular MLPDL::ML::Engine::XGBoost, MLPack, Preprocess, Metricsxgboost, scikit-learn, lightgbmNear Parity: Execution time is dominated by libxgboost and C++ routines.
    Model Inference & Quantized LLMsPDL::ML::Engine::ONNX, Alien::GGML, Safetensors, GGUFonnxruntime, llama-cpp-python, safetensorsNear Parity: Native C/C++ execution once tensors and weights are memory-mapped.
    Dense Vector Search & RAGSentencePiece, Tokenisers, FAISS, PDL::ML::RAGsentencepiece, tokenizers, faiss, langchainNear Parity: Tokenization, embedding, and FAISS indexing all run in native C++ memory.
    Frontier Model Training & AutodiffLimited (no native compiler-level autodiff or XLA/Triton stack)PyTorch, JAX, TensorFlow, TritonPython / C++ Lead: Multi-node GPU/TPU training, reverse-mode autodiff, and kernel fusion (torch.compile, XLA) remain Python/Julia/C++-centric.

    Once data is resident in PDL ndarrays, chaining PDL::IO::DuckDB → PDL::ML::Preprocess → PDL::ML::Engine::XGBoost for tabular scoring, or PDL::ML::Token::SentencePiece → PDL::ML::Engine::ONNX → PDL::ML::Vector::FAISS → PDL::ML::RAG for dense retrieval, executes inside the exact same C and C++ libraries powering Python and Rust services.


    5. Linux Distro Readiness: Debian trixie (and Enterprise Linux EPEL 9)

    For Debian Developers and systems administrators, the best surprise is how much of the heavy C and C++ lifting is already packaged in Debian main thanks to the Debian Science and Debian Deep Learning teams. On a standard Debian 13 (trixie) machine today, apt already provides DFSG-compliant shared libraries and headers for the core numerical and ML runtimes:

    • pdl (1:2.100-1)
    • libonnxruntime-dev (1.21.0+dfsg-1)
    • libxgboost-dev (3.0.0-1)
    • libfaiss-dev (1.11.0-3)
    • libmlpack-dev (4.6.0-1)
    • libsentencepiece-dev (0.2.0-1+b3)
    • libprotobuf-dev (3.21.12-11+deb13u1)

    (Enterprise Linux users benefit similarly: on Rocky Linux 9 and AlmaLinux 9, perl-PDL is available straight from EPEL 9.) Where an upstream C/C++ runtime is not yet packaged by the OS, Alien::GGML and Alien::LibTorch use Alien::Build‘s standard system-first probe: honoring pkg-config distro libraries automatically whenever present (as Debian’s pkg-perl policy expects) and falling back to an isolated build only when needed.


    6. What’s Next

    Paired with the Cloud gRPC, Protobuf, and Gemini SDK stack, Perl now has a cohesive story across both remote cloud AI orchestration and local C/C++ columnar analytics, vector search, and model inference. Over the coming weeks, our focus is on four concrete milestones:

    • Upstream review & C++ header cleanup: Working through maintainer feedback across all 16 PDLPorters pull requests (including Alien::GGML and Alien::LibTorch) and resolving the C++ complex header collision in PDLPorters/pdl#563.
    • Tutorial-driven executable tests: Shipping end-to-end machine learning tutorials as executable .t test suites, including classic bioinformatics tabular classification benchmarks on the UCI E. coli and Yeast protein subcellular localization datasets and weighted k-NN pipelines inspired by PSORT and WoLF PSORT.
    • Initial CPAN releases under PDLPorters: Cutting initial CPAN releases once PDLPorters co-maintainers sign off on the public APIs and type contracts.
    • Debian pkg-perl packaging: Packaging the stack for Debian starting with libpdl-io-arrow-perl and libpdl-io-protobuf-perl alongside the existing trixie/forky C++ libraries.

    If you use PDL, work on bioinformatics or scientific computing in Perl, or help maintain numerical packages in Debian, feedback on PDLPorters/pdl#562 and the 16 satellite pull requests is very welcome.