Skip to content

include/tenzr/execution/jit_cache.h

Namespaces

Name
tenzr

Classes

Name
struct tenzr::CachedExecutable
A compiled PJRT executable together with its hash and the shape and dtype descriptors of its inputs and outputs.
class tenzr::JitCache
Process-wide cache of compiled executables keyed by namespaced structural hashes.

Source code

// Copyright 2026 The Tenzr Project Authors
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef TENZR_EXECUTION_JIT_CACHE_H_
#define TENZR_EXECUTION_JIT_CACHE_H_

#include <xla/pjrt/c/pjrt_c_api.h>

#include <cstdint>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <vector>

#include "tenzr/frontend/dtype.h"
#include "tenzr/frontend/shape.h"

namespace tenzr {

  struct CachedExecutable {
    uint64_t hash{0};

    PJRT_LoadedExecutable* executable{nullptr};

    std::vector<Shape> in_shapes;
    std::vector<DType> in_dtypes;

    std::vector<Shape> out_shapes;
    std::vector<DType> out_dtypes;

    ~CachedExecutable();
  };

  class JitCache {
   public:
    static JitCache& Instance();

    static constexpr uint64_t kEagerKeyDomain = 0xA57D0C0DE5EEDULL;
    static constexpr uint64_t kJitKeyDomain = 0x117C0DE5EED0ULL;

    [[nodiscard]] static uint64_t DomainKey(uint64_t domain, uint64_t hash) noexcept { return domain ^ (hash + 0x9E3779B97F4A7C15ULL); }

    JitCache() = default;

    ~JitCache();

    JitCache(const JitCache&) = delete;
    JitCache& operator=(const JitCache&) = delete;

    std::shared_ptr<CachedExecutable> Get(uint64_t hash);

    void Put(uint64_t hash, std::shared_ptr<CachedExecutable> exec);

    bool Contains(uint64_t hash) const;

    size_t Size() const;

    void Clear();

   private:
    mutable std::mutex mutex_;
    std::unordered_map<uint64_t, std::shared_ptr<CachedExecutable>> cache_;
  };

}  // namespace tenzr

#endif  // TENZR_EXECUTION_JIT_CACHE_H_