MCPcopy Create free account
hub / github.com/DeepRec-AI/DeepRec / CachedLookup

Method CachedLookup

tensorflow/python/util/util.cc:146–186  ·  view source on GitHub ↗

Caches successful executions of the one-argument (PyObject*) callable "ternary_predicate" based on the type of "o". -1 from the callable indicates an unsuccessful check (not cached), 0 indicates that "o"'s type does not match the predicate, and 1 indicates that it does. Used to avoid calling back into Python for expensive isinstance checks.

Source from the content-addressed store, hash-verified

144 // does not match the predicate, and 1 indicates that it does. Used to avoid
145 // calling back into Python for expensive isinstance checks.
146 int CachedLookup(PyObject* o) {
147 // Try not to return to Python - see if the type has already been seen
148 // before.
149
150 auto* type = Py_TYPE(o);
151
152 {
153 tf_shared_lock l(type_to_sequence_map_mu_);
154 auto it = type_to_sequence_map_.find(type);
155 if (it != type_to_sequence_map_.end()) {
156 return it->second;
157 }
158 }
159
160 int check_result = ternary_predicate_(o);
161
162 if (check_result == -1) {
163 return -1; // Type check error, not cached.
164 }
165
166 // NOTE: This is never decref'd as long as the object lives, which is likely
167 // forever, but we don't want the type to get deleted as long as it is in
168 // the map. This should not be too much of a leak, as there should only be a
169 // relatively small number of types in the map, and an even smaller number
170 // that are eligible for decref. As a precaution, we limit the size of the
171 // map to 1024.
172 {
173 mutex_lock l(type_to_sequence_map_mu_);
174 if (type_to_sequence_map_.size() < kMaxItemsInCache) {
175 Py_INCREF(type);
176 auto insert_result = type_to_sequence_map_.insert({type, check_result});
177 if (!insert_result.second) {
178 // The type was added to the cache by a concurrent thread after we
179 // looked it up above.
180 Py_DECREF(type);
181 }
182 }
183 }
184
185 return check_result;
186 }
187
188 private:
189 std::function<int(PyObject*)> ternary_predicate_;

Callers 10

IsMappingHelperFunction · 0.80
IsMappingViewHelperFunction · 0.80
IsAttrsHelperFunction · 0.80
IsIndexedSlicesHelperFunction · 0.80
IsTensorHelperFunction · 0.80
IsResourceVariableHelperFunction · 0.80
IsVariableHelperFunction · 0.80
IsSequenceHelperFunction · 0.80
IsCompositeTensorHelperFunction · 0.80
IsTypeSpecHelperFunction · 0.80

Calls 4

findMethod · 0.45
endMethod · 0.45
sizeMethod · 0.45
insertMethod · 0.45

Tested by

no test coverage detected