MCPcopy Create free account
hub / github.com/ml-explore/mlx-data / dynamic_batch_

Method dynamic_batch_

mlx/data/buffer/DynamicBatch.cpp:68–207  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

66 skipped_samples_(std::get<2>(buffer_with_sizes)) {};
67
68std::tuple<std::shared_ptr<Buffer>, std::vector<int64_t>, std::vector<int64_t>>
69DynamicBatch::dynamic_batch_(
70 const std::shared_ptr<Buffer>& buffer,
71 const std::shared_ptr<Buffer>& ref_size_buffer,
72 const std::string& key,
73 int64_t min_data_size,
74 int64_t max_data_size,
75 const std::unordered_map<std::string, int>& batch_dims,
76 bool drop_outliers) {
77 int64_t n = buffer->size();
78
79 if (ref_size_buffer && (ref_size_buffer->size() != n)) {
80 throw std::runtime_error(
81 "DynamicBatch: buffer and reference size buffer do not match in size");
82 }
83
84 // get sample shapes
85 std::vector<std::vector<int64_t>> sample_shapes(n);
86 for (int64_t i = 0; i < n; i++) {
87 if (ref_size_buffer) {
88 auto sample = ref_size_buffer->get(i);
89 auto array = mlx::data::sample::check_key(sample, key, ArrayType::Int64);
90 sample_shapes[i].insert(
91 sample_shapes[i].begin(),
92 array->data<int64_t>(),
93 array->data<int64_t>() + array->size());
94 } else {
95 auto sample = buffer->get(i);
96 auto array = mlx::data::sample::check_key(sample, key, ArrayType::Any);
97 sample_shapes[i] = array->shape();
98 }
99 }
100
101 // get sample sizes
102 std::vector<int64_t> sample_sizes(n, 0);
103 for (int64_t i = 0; i < n; i++) {
104 auto& shape = sample_shapes[i];
105 if (shape.size() > 0) {
106 int64_t size = shape[0];
107 for (int i = 1; i < shape.size(); i++) {
108 size *= shape[i];
109 }
110 sample_sizes[i] = size;
111 }
112 }
113
114 // sort (if we do not batch everything)
115 std::vector<int64_t> sorted_samples(sample_sizes.size());
116 std::iota(sorted_samples.begin(), sorted_samples.end(), 0);
117 if (max_data_size > 0) {
118 std::stable_sort(
119 sorted_samples.begin(),
120 sorted_samples.end(),
121 [&sample_sizes](size_t i1, size_t i2) {
122 return sample_sizes[i1] < sample_sizes[i2];
123 });
124 }
125

Callers

nothing calls this directly

Calls 10

check_keyFunction · 0.85
BatchShapeClass · 0.85
insertMethod · 0.80
findMethod · 0.80
clearMethod · 0.80
num_sampleMethod · 0.80
sizeMethod · 0.45
getMethod · 0.45
shapeMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected