2024-01-27 05:45:30 +08:00
|
|
|
// Copyright © 2023-2024 Apple Inc.
|
2023-12-01 03:12:53 +08:00
|
|
|
|
2024-03-05 12:02:26 +08:00
|
|
|
#pragma once
|
|
|
|
|
2023-11-30 02:52:08 +08:00
|
|
|
namespace mlx::core::detail {
|
|
|
|
|
|
|
|
std::pair<std::vector<array>, std::vector<array>> vmap_trace(
|
|
|
|
const std::function<std::vector<array>(const std::vector<array>&)>& fun,
|
|
|
|
const std::vector<array>& inputs,
|
|
|
|
const std::vector<int>& in_axes);
|
|
|
|
|
|
|
|
std::vector<array> vmap_replace(
|
|
|
|
const std::vector<array>& inputs,
|
|
|
|
const std::vector<array>& s_inputs,
|
|
|
|
const std::vector<array>& s_outputs,
|
|
|
|
const std::vector<int>& in_axes,
|
|
|
|
const std::vector<int>& out_axes);
|
|
|
|
|
2024-01-08 07:16:51 +08:00
|
|
|
// Create an InTracing object during tracing operations to signify to the rest
|
|
|
|
// of the codebase that we are during tracing so evals should not throw away
|
|
|
|
// the graph.
|
|
|
|
struct InTracing {
|
2025-01-10 03:04:24 +08:00
|
|
|
explicit InTracing(bool dynamic = false) {
|
|
|
|
trace_stack.push_back(dynamic);
|
2024-01-08 07:16:51 +08:00
|
|
|
}
|
|
|
|
~InTracing() {
|
2025-01-10 03:04:24 +08:00
|
|
|
trace_stack.pop_back();
|
2024-01-08 07:16:51 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
static bool in_tracing() {
|
2025-01-10 03:04:24 +08:00
|
|
|
return !trace_stack.empty();
|
|
|
|
}
|
|
|
|
static bool in_dynamic_tracing() {
|
|
|
|
// compile is always and only the outer-most transform
|
|
|
|
return in_tracing() && trace_stack.front();
|
2024-01-08 07:16:51 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2025-01-10 03:04:24 +08:00
|
|
|
static std::vector<bool> trace_stack;
|
2024-01-08 07:16:51 +08:00
|
|
|
};
|
|
|
|
|
2024-07-11 09:00:01 +08:00
|
|
|
struct RetainGraph {
|
|
|
|
RetainGraph() {
|
|
|
|
tracing_counter++;
|
|
|
|
}
|
|
|
|
~RetainGraph() {
|
|
|
|
tracing_counter--;
|
|
|
|
}
|
|
|
|
|
|
|
|
static bool retain_graph() {
|
|
|
|
return tracing_counter > 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
static int tracing_counter;
|
|
|
|
};
|
|
|
|
|
2025-01-10 03:04:24 +08:00
|
|
|
/** Return true if we are currently performing a function transformation in
|
|
|
|
* order to keep the graph when evaluating tracer arrays. */
|
|
|
|
inline bool in_tracing() {
|
|
|
|
return detail::InTracing::in_tracing();
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Return true if we are in a dynamic (shapeless) trace used for compiling or
|
|
|
|
* exporting graphs with dynamic shapes. */
|
|
|
|
inline bool in_dynamic_tracing() {
|
|
|
|
return detail::InTracing::in_dynamic_tracing();
|
|
|
|
}
|
|
|
|
|
|
|
|
inline bool retain_graph() {
|
|
|
|
return detail::RetainGraph::retain_graph();
|
|
|
|
}
|
|
|
|
|
2023-11-30 02:52:08 +08:00
|
|
|
} // namespace mlx::core::detail
|