code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_transform_conversation_with_system_prompt_column(
mock_load_data,
mock_tokenizer,
mock_processor,
sample_dataset_example_with_system_prompt,
):
"""Test conversation transformation with system prompt from column."""
mock_load_data.return_value = pd.DataFrame()
dataset = HuggingFaceVi... | Test conversation transformation with system prompt from column. | test_transform_conversation_with_system_prompt_column | python | oumi-ai/oumi | tests/unit/datasets/test_huggingface_vision_dataset.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/datasets/test_huggingface_vision_dataset.py | Apache-2.0 |
def test_transform_conversation_no_answer_column(
mock_load_data, mock_tokenizer, mock_processor, sample_dataset_example_no_answer
):
"""Test conversation transformation without answer column."""
mock_load_data.return_value = pd.DataFrame()
dataset = HuggingFaceVisionDataset(
hf_dataset_path="te... | Test conversation transformation without answer column. | test_transform_conversation_no_answer_column | python | oumi-ai/oumi | tests/unit/datasets/test_huggingface_vision_dataset.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/datasets/test_huggingface_vision_dataset.py | Apache-2.0 |
def test_transform_conversation_missing_column(
mock_load_data, mock_tokenizer, mock_processor
):
"""Test conversation transformation with missing required column."""
mock_load_data.return_value = pd.DataFrame()
dataset = HuggingFaceVisionDataset(
hf_dataset_path="test/dataset",
image_co... | Test conversation transformation with missing required column. | test_transform_conversation_missing_column | python | oumi-ai/oumi | tests/unit/datasets/test_huggingface_vision_dataset.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/datasets/test_huggingface_vision_dataset.py | Apache-2.0 |
def test_gemini_convert_conversation(gemini_engine, generation_params):
"""Test basic conversation conversion without special features."""
conversation = Conversation(
messages=[
Message(content="Hello", role=Role.USER),
Message(content="Hi there!", role=Role.ASSISTANT),
... | Test basic conversation conversion without special features. | test_gemini_convert_conversation | python | oumi-ai/oumi | tests/unit/inference/test_gemini_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_gemini_inference_engine.py | Apache-2.0 |
def test_gemini_convert_conversation_with_guided_decoding(
gemini_engine, generation_params
):
"""Test conversation conversion with JSON schema guided decoding."""
class TestSchema(pydantic.BaseModel):
name: str
age: int
generation_params.guided_decoding = GuidedDecodingParams(json=Tes... | Test conversation conversion with JSON schema guided decoding. | test_gemini_convert_conversation_with_guided_decoding | python | oumi-ai/oumi | tests/unit/inference/test_gemini_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_gemini_inference_engine.py | Apache-2.0 |
def test_gemini_convert_conversation_with_json_schema_variations(
gemini_engine, generation_params, json_schema
):
"""Test conversation conversion with different JSON schema formats."""
generation_params.guided_decoding = GuidedDecodingParams(json=json_schema)
conversation = Conversation(
messag... | Test conversation conversion with different JSON schema formats. | test_gemini_convert_conversation_with_json_schema_variations | python | oumi-ai/oumi | tests/unit/inference/test_gemini_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_gemini_inference_engine.py | Apache-2.0 |
def test_gemini_convert_conversation_invalid_schema(gemini_engine, generation_params):
"""Test that invalid schema types raise appropriate errors."""
generation_params.guided_decoding = GuidedDecodingParams(json=123) # Invalid type
conversation = Conversation(
messages=[
Message(content... | Test that invalid schema types raise appropriate errors. | test_gemini_convert_conversation_invalid_schema | python | oumi-ai/oumi | tests/unit/inference/test_gemini_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_gemini_inference_engine.py | Apache-2.0 |
def test_gemini_infer_from_file(gemini_engine, inference_config, tmp_path):
"""Test file-based inference with Gemini."""
conversation = Conversation(
messages=[
Message(content="Hello", role=Role.USER),
]
)
input_file = tmp_path / "input.jsonl"
with open(input_file, "w")... | Test file-based inference with Gemini. | test_gemini_infer_from_file | python | oumi-ai/oumi | tests/unit/inference/test_gemini_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_gemini_inference_engine.py | Apache-2.0 |
def _mock_engine(engine_class):
"""Mock the engine to avoid loading non-existent models."""
mock_tokenizer = mock.MagicMock()
mock_tokenizer.pad_token_id = 0
mock_tokenizer.eos_token_id = 0
mock_tokenizer.eos_token = "<eos>"
mock_model = mock.MagicMock()
mock_model.generate = mock.MagicMock... | Mock the engine to avoid loading non-existent models. | _mock_engine | python | oumi-ai/oumi | tests/unit/inference/test_generation_params.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_generation_params.py | Apache-2.0 |
def test_supported_params_are_accessed(engine_class, model_params, sample_conversation):
"""Test that all supported parameters are actually accessed during inference."""
if _should_skip_engine(engine_class):
pytest.skip(f"{engine_class.__name__} is not available")
mock_ctx = _mock_engine(engine_cla... | Test that all supported parameters are actually accessed during inference. | test_supported_params_are_accessed | python | oumi-ai/oumi | tests/unit/inference/test_generation_params.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_generation_params.py | Apache-2.0 |
def _mock_engine(engine_class):
"""Mock the engine to avoid loading non-existent models."""
mock_tokenizer = mock.MagicMock()
mock_tokenizer.pad_token_id = 0
mock_tokenizer.eos_token_id = 0
mock_tokenizer.eos_token = "<eos>"
mock_model = mock.MagicMock()
mock_model.generate = mock.MagicMock... | Mock the engine to avoid loading non-existent models. | _mock_engine | python | oumi-ai/oumi | tests/unit/inference/test_inference_engine_init.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_inference_engine_init.py | Apache-2.0 |
def test_local_engine_init_with_model_params(engine_class):
"""Test that local engines can be initialized with just model params."""
model_params = ModelParams(model_name="test-model")
mock_engine_class = _mock_engine(engine_class)
with mock_engine_class:
engine = engine_class(model_params=model... | Test that local engines can be initialized with just model params. | test_local_engine_init_with_model_params | python | oumi-ai/oumi | tests/unit/inference/test_inference_engine_init.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_inference_engine_init.py | Apache-2.0 |
def test_remote_engine_init_with_model_and_remote_params(engine_class):
"""Test that remote engines can be initialized with both model and remote params."""
model_params = ModelParams(model_name="test-model")
remote_params = RemoteParams(api_url="http://test.com", api_key="test-key")
mock_engine_class =... | Test that remote engines can be initialized with both model and remote params. | test_remote_engine_init_with_model_and_remote_params | python | oumi-ai/oumi | tests/unit/inference/test_inference_engine_init.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_inference_engine_init.py | Apache-2.0 |
def test_engine_init_missing_model_params_fails(engine_class):
"""Test that all engines fail when initialized without model params."""
remote_params = RemoteParams(api_url="http://test.com", api_key="test-key")
with pytest.raises(TypeError):
if engine_class in LOCAL_ENGINES:
engine_class... | Test that all engines fail when initialized without model params. | test_engine_init_missing_model_params_fails | python | oumi-ai/oumi | tests/unit/inference/test_inference_engine_init.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_inference_engine_init.py | Apache-2.0 |
def test_engine_init_with_invalid_params_fails(engine_class):
"""Test that all engines fail when initialized with invalid params."""
with pytest.raises(TypeError):
engine_class(invalid_param="test") # Should fail - invalid param | Test that all engines fail when initialized with invalid params. | test_engine_init_with_invalid_params_fails | python | oumi-ai/oumi | tests/unit/inference/test_inference_engine_init.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_inference_engine_init.py | Apache-2.0 |
def test_local_engine_config_overrides_constructor_params(engine_class):
"""Test that InferenceConfig params override constructor params."""
# Initialize with one set of params
init_model_params = ModelParams(
model_name="init-model",
model_max_length=128,
torch_dtype_str="float32",
... | Test that InferenceConfig params override constructor params. | test_local_engine_config_overrides_constructor_params | python | oumi-ai/oumi | tests/unit/inference/test_inference_engine_init.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_inference_engine_init.py | Apache-2.0 |
def test_remote_engine_config_overrides_constructor_params(engine_class):
"""Test that InferenceConfig params override constructor params."""
# Initialize with one set of params
init_model_params = ModelParams(
model_name="init-model",
model_max_length=128,
)
init_remote_params = Rem... | Test that InferenceConfig params override constructor params. | test_remote_engine_config_overrides_constructor_params | python | oumi-ai/oumi | tests/unit/inference/test_inference_engine_init.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_inference_engine_init.py | Apache-2.0 |
def test_engine_config_partial_override(engine_class):
"""Test that InferenceConfig partially overrides constructor params."""
# Initialize with full params
init_model_params = ModelParams(
model_name="init-model",
model_max_length=128,
torch_dtype_str="float32",
)
init_remot... | Test that InferenceConfig partially overrides constructor params. | test_engine_config_partial_override | python | oumi-ai/oumi | tests/unit/inference/test_inference_engine_init.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_inference_engine_init.py | Apache-2.0 |
def test_all_inference_engine_types_in_engine_map():
"""Test that all InferenceEngineType values are present in ENGINE_MAP."""
for engine_type in InferenceEngineType:
assert engine_type in ENGINE_MAP, (
f"Missing engine type {engine_type} in ENGINE_MAP"
) | Test that all InferenceEngineType values are present in ENGINE_MAP. | test_all_inference_engine_types_in_engine_map | python | oumi-ai/oumi | tests/unit/inference/test_inference_engine_init.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_inference_engine_init.py | Apache-2.0 |
def test_build_all_inference_engines():
"""Test that all inference engines can be built using the builder."""
model_params = ModelParams(model_name="test-model")
remote_params = RemoteParams(api_url="http://test.com", api_key="test-key")
for engine_type in InferenceEngineType:
engine_class = EN... | Test that all inference engines can be built using the builder. | test_build_all_inference_engines | python | oumi-ai/oumi | tests/unit/inference/test_inference_engine_init.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_inference_engine_init.py | Apache-2.0 |
def test_convert_conversation_to_api_input_with_json_schema():
"""Test conversion with JSON schema guided decoding."""
class ResponseSchema(BaseModel):
answer: str
confidence: float
engine = RemoteInferenceEngine(
_get_default_model_params(), remote_params=RemoteParams(api_url=_TAR... | Test conversion with JSON schema guided decoding. | test_convert_conversation_to_api_input_with_json_schema | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_convert_conversation_to_api_input_with_invalid_guided_decoding():
"""Test conversion with invalid guided decoding raises error."""
engine = RemoteInferenceEngine(
_get_default_model_params(), remote_params=RemoteParams(api_url=_TARGET_SERVER)
)
conversation = Conversation(
messa... | Test conversion with invalid guided decoding raises error. | test_convert_conversation_to_api_input_with_invalid_guided_decoding | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_convert_conversation_to_api_input_with_dict_schema():
"""Test conversion with JSON schema provided as a dictionary."""
engine = RemoteInferenceEngine(
_get_default_model_params(), remote_params=RemoteParams(api_url=_TARGET_SERVER)
)
conversation = Conversation(
messages=[
... | Test conversion with JSON schema provided as a dictionary. | test_convert_conversation_to_api_input_with_dict_schema | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_convert_conversation_to_api_input_with_json_string_schema():
"""Test conversion with JSON schema provided as a JSON string."""
engine = RemoteInferenceEngine(
_get_default_model_params(), remote_params=RemoteParams(api_url=_TARGET_SERVER)
)
conversation = Conversation(
messages=... | Test conversion with JSON schema provided as a JSON string. | test_convert_conversation_to_api_input_with_json_string_schema | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_convert_conversation_to_api_input_with_invalid_json_string():
"""Test conversion with invalid JSON string raises error."""
engine = RemoteInferenceEngine(
_get_default_model_params(), remote_params=RemoteParams(api_url=_TARGET_SERVER)
)
conversation = Conversation(
messages=[
... | Test conversion with invalid JSON string raises error. | test_convert_conversation_to_api_input_with_invalid_json_string | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_convert_conversation_to_api_input_with_unsupported_schema_type():
"""Test conversion with unsupported schema type raises error."""
engine = RemoteInferenceEngine(
_get_default_model_params(), remote_params=RemoteParams(api_url=_TARGET_SERVER)
)
conversation = Conversation(
messa... | Test conversion with unsupported schema type raises error. | test_convert_conversation_to_api_input_with_unsupported_schema_type | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_infer_online_handles_content_type_text_plain():
"""Test that the engine can handle text/plain responses and parse them as JSON."""
with aioresponses() as m:
m.post(
_TARGET_SERVER,
status=200,
body=json.dumps(
{
"choices": ... | Test that the engine can handle text/plain responses and parse them as JSON. | test_infer_online_handles_content_type_text_plain | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_infer_online_handles_invalid_content():
"""Test that the engine properly handles invalid content responses."""
with aioresponses() as m:
m.post(
_TARGET_SERVER,
status=200,
body=json.dumps({"error": {"message": "Invalid JSON content"}}),
content_t... | Test that the engine properly handles invalid content responses. | test_infer_online_handles_invalid_content | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_infer_online_exponential_backoff():
"""Test that the engine implements exponential backoff correctly."""
sleep_calls = []
async def mock_sleep(delay):
sleep_calls.append(delay)
def callback(url, **kwargs):
# Fail until the last attempt
if len(sleep_calls) < 3:
... | Test that the engine implements exponential backoff correctly. | test_infer_online_exponential_backoff | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_non_retriable_errors(mock_asyncio_sleep):
"""Test that certain HTTP status codes are not retried."""
non_retriable_codes = [400, 401, 403, 404, 422]
error_messages = {
400: "Bad request error",
401: "Unauthorized error",
403: "Forbidden error",
404: "Not found error"... | Test that certain HTTP status codes are not retried. | test_non_retriable_errors | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_response_processing_error(mock_asyncio_sleep):
"""Test handling of errors during response processing."""
with aioresponses() as m:
m.post(
_TARGET_SERVER,
status=200,
payload={"choices": [{"invalid": "response"}]}, # Missing required fields
)
... | Test handling of errors during response processing. | test_response_processing_error | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_malformed_json_response(mock_asyncio_sleep):
"""Test handling of malformed JSON responses."""
with aioresponses() as m:
m.post(
_TARGET_SERVER,
status=200,
body="Invalid JSON {",
content_type="application/json",
)
m.post(
... | Test handling of malformed JSON responses. | test_malformed_json_response | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_unexpected_error_handling(mock_asyncio_sleep):
"""Test handling of unexpected errors during API calls."""
def raise_unexpected(*args, **kwargs):
raise ValueError("Unexpected internal error")
with aioresponses() as m:
m.post(_TARGET_SERVER, callback=raise_unexpected)
engin... | Test handling of unexpected errors during API calls. | test_unexpected_error_handling | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_list_response_error_handling():
"""Test handling of list-type error responses."""
with aioresponses() as m:
m.post(
_TARGET_SERVER,
status=500,
payload=[{"error": {"message": "Internal server error"}}],
)
engine = RemoteInferenceEngine(
... | Test handling of list-type error responses. | test_list_response_error_handling | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_retry_with_different_errors():
"""Test retry behavior with different types of errors on each attempt."""
attempt = 0
def get_response(*args, **kwargs):
nonlocal attempt
attempt += 1
if attempt == 1:
raise aiohttp.ClientError("Network error")
elif attemp... | Test retry behavior with different types of errors on each attempt. | test_retry_with_different_errors | python | oumi-ai/oumi | tests/unit/inference/test_remote_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_remote_inference_engine.py | Apache-2.0 |
def test_convert_conversation_to_api_input(sambanova_engine):
"""Test conversion of conversation to SambaNova API input format."""
conversation = Conversation(
messages=[
Message(content="System message", role=Role.SYSTEM),
Message(content="User message", role=Role.USER),
... | Test conversion of conversation to SambaNova API input format. | test_convert_conversation_to_api_input | python | oumi-ai/oumi | tests/unit/inference/test_sambanova_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_sambanova_inference_engine.py | Apache-2.0 |
def test_convert_api_output_to_conversation(sambanova_engine):
"""Test conversion of SambaNova API output to conversation."""
original_conversation = Conversation(
messages=[
Message(content="User message", role=Role.USER),
],
metadata={"key": "value"},
conversation_i... | Test conversion of SambaNova API output to conversation. | test_convert_api_output_to_conversation | python | oumi-ai/oumi | tests/unit/inference/test_sambanova_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_sambanova_inference_engine.py | Apache-2.0 |
def test_convert_api_output_to_conversation_error_handling(sambanova_engine):
"""Test error handling in API output conversion."""
original_conversation = Conversation(
messages=[Message(content="User message", role=Role.USER)]
)
# Test empty choices
with pytest.raises(RuntimeError, match="N... | Test error handling in API output conversion. | test_convert_api_output_to_conversation_error_handling | python | oumi-ai/oumi | tests/unit/inference/test_sambanova_inference_engine.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/inference/test_sambanova_inference_engine.py | Apache-2.0 |
def _verify_no_extra_import(extra_module: str):
"""Verifies that extra modules are not imported."""
import sys
import oumi.launcher # noqa
assert extra_module not in sys.modules, f"{extra_module} was imported." | Verifies that extra modules are not imported. | _verify_no_extra_import | python | oumi-ai/oumi | tests/unit/launcher/test_launcher.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/launcher/test_launcher.py | Apache-2.0 |
async def test_get_failure_reason_from_response_with_json_response():
"""Test handling of non-retryable errors with JSON response."""
mock_response = AsyncMock(spec=aiohttp.ClientResponse)
mock_response.status = 400
mock_response.json.return_value = {"error": {"message": "Invalid request"}}
result ... | Test handling of non-retryable errors with JSON response. | test_get_failure_reason_from_response_with_json_response | python | oumi-ai/oumi | tests/unit/utils/test_http.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/utils/test_http.py | Apache-2.0 |
async def test_get_failure_reason_from_response_with_list_response():
"""Test handling of non-retryable errors with list response."""
mock_response = AsyncMock(spec=aiohttp.ClientResponse)
mock_response.status = 400
mock_response.json.return_value = [{"error": {"message": "Invalid request"}}]
resul... | Test handling of non-retryable errors with list response. | test_get_failure_reason_from_response_with_list_response | python | oumi-ai/oumi | tests/unit/utils/test_http.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/utils/test_http.py | Apache-2.0 |
async def test_get_failure_reason_from_response_with_empty_response():
"""Test handling of non-retryable errors with empty response."""
mock_response = AsyncMock(spec=aiohttp.ClientResponse)
mock_response.status = 400
mock_response.json.return_value = {}
result = await get_failure_reason_from_respo... | Test handling of non-retryable errors with empty response. | test_get_failure_reason_from_response_with_empty_response | python | oumi-ai/oumi | tests/unit/utils/test_http.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/utils/test_http.py | Apache-2.0 |
async def test_get_failure_reason_from_response_with_json_error():
"""Test handling of non-retryable errors when JSON parsing fails."""
mock_response = AsyncMock(spec=aiohttp.ClientResponse)
mock_response.status = 400
mock_response.json.side_effect = Exception("JSON decode error")
result = await ge... | Test handling of non-retryable errors when JSON parsing fails. | test_get_failure_reason_from_response_with_json_error | python | oumi-ai/oumi | tests/unit/utils/test_http.py | https://github.com/oumi-ai/oumi/blob/master/tests/unit/utils/test_http.py | Apache-2.0 |
def face_distance(face_encodings, face_to_compare):
"""
Given a list of face encodings, compare them to a known face encoding and get a euclidean distance
for each comparison face. The distance tells you how similar the faces are.
:param faces: List of face encodings to compare
:param face_to_compar... |
Given a list of face encodings, compare them to a known face encoding and get a euclidean distance
for each comparison face. The distance tells you how similar the faces are.
:param faces: List of face encodings to compare
:param face_to_compare: A face encoding to compare against
:return: A numpy ... | face_distance | python | davidsandberg/facenet | contributed/clustering.py | https://github.com/davidsandberg/facenet/blob/master/contributed/clustering.py | MIT |
def _chinese_whispers(encoding_list, threshold=0.55, iterations=20):
""" Chinese Whispers Algorithm
Modified from Alex Loveless' implementation,
http://alexloveless.co.uk/data/chinese-whispers-graph-clustering-in-python/
Inputs:
encoding_list: a list of facial encodings from face_recognition
... | Chinese Whispers Algorithm
Modified from Alex Loveless' implementation,
http://alexloveless.co.uk/data/chinese-whispers-graph-clustering-in-python/
Inputs:
encoding_list: a list of facial encodings from face_recognition
threshold: facial match threshold,default 0.6
iterations: sin... | _chinese_whispers | python | davidsandberg/facenet | contributed/clustering.py | https://github.com/davidsandberg/facenet/blob/master/contributed/clustering.py | MIT |
def cluster_facial_encodings(facial_encodings):
""" Cluster facial encodings
Intended to be an optional switch for different clustering algorithms, as of right now
only chinese whispers is available.
Input:
facial_encodings: (image_path, facial_encoding) dictionary of facial en... | Cluster facial encodings
Intended to be an optional switch for different clustering algorithms, as of right now
only chinese whispers is available.
Input:
facial_encodings: (image_path, facial_encoding) dictionary of facial encodings
Output:
sorted_clusters: a... | cluster_facial_encodings | python | davidsandberg/facenet | contributed/clustering.py | https://github.com/davidsandberg/facenet/blob/master/contributed/clustering.py | MIT |
def compute_facial_encodings(sess,images_placeholder,embeddings,phase_train_placeholder,image_size,
embedding_size,nrof_images,nrof_batches,emb_array,batch_size,paths):
""" Compute Facial Encodings
Given a set of images, compute the facial encodings of each face detected in the images a... | Compute Facial Encodings
Given a set of images, compute the facial encodings of each face detected in the images and
return them. If no faces, or more than one face found, return nothing for that image.
Inputs:
image_paths: a list of image paths
Outputs:
facia... | compute_facial_encodings | python | davidsandberg/facenet | contributed/clustering.py | https://github.com/davidsandberg/facenet/blob/master/contributed/clustering.py | MIT |
def main(args):
""" Main
Given a list of images, save out facial encoding data files and copy
images into folders of face clusters.
"""
from os.path import join, basename, exists
from os import makedirs
import numpy as np
import shutil
import sys
if not exists(args.output):
... | Main
Given a list of images, save out facial encoding data files and copy
images into folders of face clusters.
| main | python | davidsandberg/facenet | contributed/clustering.py | https://github.com/davidsandberg/facenet/blob/master/contributed/clustering.py | MIT |
def triplet_loss(anchor, positive, negative, alpha):
"""Calculate the triplet loss according to the FaceNet paper
Args:
anchor: the embeddings for the anchor images.
positive: the embeddings for the positive images.
negative: the embeddings for the negative images.
Returns:
t... | Calculate the triplet loss according to the FaceNet paper
Args:
anchor: the embeddings for the anchor images.
positive: the embeddings for the positive images.
negative: the embeddings for the negative images.
Returns:
the triplet loss according to the FaceNet paper as a float te... | triplet_loss | python | davidsandberg/facenet | src/facenet.py | https://github.com/davidsandberg/facenet/blob/master/src/facenet.py | MIT |
def center_loss(features, label, alfa, nrof_classes):
"""Center loss based on the paper "A Discriminative Feature Learning Approach for Deep Face Recognition"
(http://ydwen.github.io/papers/WenECCV16.pdf)
"""
nrof_features = features.get_shape()[1]
centers = tf.get_variable('centers', [nrof_class... | Center loss based on the paper "A Discriminative Feature Learning Approach for Deep Face Recognition"
(http://ydwen.github.io/papers/WenECCV16.pdf)
| center_loss | python | davidsandberg/facenet | src/facenet.py | https://github.com/davidsandberg/facenet/blob/master/src/facenet.py | MIT |
def _add_loss_summaries(total_loss):
"""Add summaries for losses.
Generates moving average for all losses and associated summaries for
visualizing the performance of the network.
Args:
total_loss: Total loss from loss().
Returns:
loss_averages_op: op for generating moving averages ... | Add summaries for losses.
Generates moving average for all losses and associated summaries for
visualizing the performance of the network.
Args:
total_loss: Total loss from loss().
Returns:
loss_averages_op: op for generating moving averages of losses.
| _add_loss_summaries | python | davidsandberg/facenet | src/facenet.py | https://github.com/davidsandberg/facenet/blob/master/src/facenet.py | MIT |
def load(self, data_path, session, ignore_missing=False):
"""Load network weights.
data_path: The path to the numpy-serialized network weights
session: The current TensorFlow session
ignore_missing: If true, serialized weights for missing layers are ignored.
"""
data_dict... | Load network weights.
data_path: The path to the numpy-serialized network weights
session: The current TensorFlow session
ignore_missing: If true, serialized weights for missing layers are ignored.
| load | python | davidsandberg/facenet | src/align/detect_face.py | https://github.com/davidsandberg/facenet/blob/master/src/align/detect_face.py | MIT |
def feed(self, *args):
"""Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers.
"""
assert len(args) != 0
self.terminals = []
for fed_layer in args:
if isinstance(fed_layer, strin... | Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers.
| feed | python | davidsandberg/facenet | src/align/detect_face.py | https://github.com/davidsandberg/facenet/blob/master/src/align/detect_face.py | MIT |
def get_unique_name(self, prefix):
"""Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.
"""
ident = sum(t.startswith(prefix) for t, _ in self.layers.items()) + 1
return '%s_%d' % (prefix, ident) | Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.
| get_unique_name | python | davidsandberg/facenet | src/align/detect_face.py | https://github.com/davidsandberg/facenet/blob/master/src/align/detect_face.py | MIT |
def detect_face(img, minsize, pnet, rnet, onet, threshold, factor):
"""Detects faces in an image, and returns bounding boxes and points for them.
img: input image
minsize: minimum faces' size
pnet, rnet, onet: caffemodel
threshold: threshold=[th1, th2, th3], th1-3 are three steps's threshold
fac... | Detects faces in an image, and returns bounding boxes and points for them.
img: input image
minsize: minimum faces' size
pnet, rnet, onet: caffemodel
threshold: threshold=[th1, th2, th3], th1-3 are three steps's threshold
factor: the factor used to create a scaling pyramid of face sizes to detect in... | detect_face | python | davidsandberg/facenet | src/align/detect_face.py | https://github.com/davidsandberg/facenet/blob/master/src/align/detect_face.py | MIT |
def bulk_detect_face(images, detection_window_size_ratio, pnet, rnet, onet, threshold, factor):
"""Detects faces in a list of images
images: list containing input images
detection_window_size_ratio: ratio of minimum face size to smallest image dimension
pnet, rnet, onet: caffemodel
threshold: thresh... | Detects faces in a list of images
images: list containing input images
detection_window_size_ratio: ratio of minimum face size to smallest image dimension
pnet, rnet, onet: caffemodel
threshold: threshold=[th1 th2 th3], th1-3 are three steps's threshold [0-1]
factor: the factor used to create a scal... | bulk_detect_face | python | davidsandberg/facenet | src/align/detect_face.py | https://github.com/davidsandberg/facenet/blob/master/src/align/detect_face.py | MIT |
def generateBoundingBox(imap, reg, scale, t):
"""Use heatmap to generate bounding boxes"""
stride=2
cellsize=12
imap = np.transpose(imap)
dx1 = np.transpose(reg[:,:,0])
dy1 = np.transpose(reg[:,:,1])
dx2 = np.transpose(reg[:,:,2])
dy2 = np.transpose(reg[:,:,3])
y, x = np.where(imap ... | Use heatmap to generate bounding boxes | generateBoundingBox | python | davidsandberg/facenet | src/align/detect_face.py | https://github.com/davidsandberg/facenet/blob/master/src/align/detect_face.py | MIT |
def pad(total_boxes, w, h):
"""Compute the padding coordinates (pad the bounding boxes to square)"""
tmpw = (total_boxes[:,2]-total_boxes[:,0]+1).astype(np.int32)
tmph = (total_boxes[:,3]-total_boxes[:,1]+1).astype(np.int32)
numbox = total_boxes.shape[0]
dx = np.ones((numbox), dtype=np.int32)
d... | Compute the padding coordinates (pad the bounding boxes to square) | pad | python | davidsandberg/facenet | src/align/detect_face.py | https://github.com/davidsandberg/facenet/blob/master/src/align/detect_face.py | MIT |
def inception_resnet_v1(inputs, is_training=True,
dropout_keep_prob=0.8,
bottleneck_layer_size=128,
reuse=None,
scope='InceptionResnetV1'):
"""Creates the Inception Resnet V1 model.
Args:
inputs: a 4-D tensor ... | Creates the Inception Resnet V1 model.
Args:
inputs: a 4-D tensor of size [batch_size, height, width, 3].
num_classes: number of predicted classes.
is_training: whether is training or not.
dropout_keep_prob: float, the fraction to keep before final layer.
reuse: whether or not the netw... | inception_resnet_v1 | python | davidsandberg/facenet | src/models/inception_resnet_v1.py | https://github.com/davidsandberg/facenet/blob/master/src/models/inception_resnet_v1.py | MIT |
def inception_resnet_v2(inputs, is_training=True,
dropout_keep_prob=0.8,
bottleneck_layer_size=128,
reuse=None,
scope='InceptionResnetV2'):
"""Creates the Inception Resnet V2 model.
Args:
inputs: a 4-D tensor o... | Creates the Inception Resnet V2 model.
Args:
inputs: a 4-D tensor of size [batch_size, height, width, 3].
num_classes: number of predicted classes.
is_training: whether is training or not.
dropout_keep_prob: float, the fraction to keep before final layer.
reuse: whether or not the netw... | inception_resnet_v2 | python | davidsandberg/facenet | src/models/inception_resnet_v2.py | https://github.com/davidsandberg/facenet/blob/master/src/models/inception_resnet_v2.py | MIT |
def __init__(self, facePredictor):
"""
Instantiate an 'AlignDlib' object.
:param facePredictor: The path to dlib's
:type facePredictor: str
"""
assert facePredictor is not None
#pylint: disable=no-member
self.detector = dlib.get_frontal_face_detector()
... |
Instantiate an 'AlignDlib' object.
:param facePredictor: The path to dlib's
:type facePredictor: str
| __init__ | python | davidsandberg/facenet | tmp/align_dlib.py | https://github.com/davidsandberg/facenet/blob/master/tmp/align_dlib.py | MIT |
def getAllFaceBoundingBoxes(self, rgbImg):
"""
Find all face bounding boxes in an image.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:return: All face bounding boxes in an image.
:rtype: dlib.rectangles
"""
a... |
Find all face bounding boxes in an image.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:return: All face bounding boxes in an image.
:rtype: dlib.rectangles
| getAllFaceBoundingBoxes | python | davidsandberg/facenet | tmp/align_dlib.py | https://github.com/davidsandberg/facenet/blob/master/tmp/align_dlib.py | MIT |
def getLargestFaceBoundingBox(self, rgbImg, skipMulti=False):
"""
Find the largest face bounding box in an image.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:param skipMulti: Skip image if more than one face detected.
:type... |
Find the largest face bounding box in an image.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:param skipMulti: Skip image if more than one face detected.
:type skipMulti: bool
:return: The largest face bounding box in an ima... | getLargestFaceBoundingBox | python | davidsandberg/facenet | tmp/align_dlib.py | https://github.com/davidsandberg/facenet/blob/master/tmp/align_dlib.py | MIT |
def findLandmarks(self, rgbImg, bb):
"""
Find the landmarks of a face.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:param bb: Bounding box around the face to find landmarks for.
:type bb: dlib.rectangle
:return: Dete... |
Find the landmarks of a face.
:param rgbImg: RGB image to process. Shape: (height, width, 3)
:type rgbImg: numpy.ndarray
:param bb: Bounding box around the face to find landmarks for.
:type bb: dlib.rectangle
:return: Detected landmark locations.
:rtype: list of... | findLandmarks | python | davidsandberg/facenet | tmp/align_dlib.py | https://github.com/davidsandberg/facenet/blob/master/tmp/align_dlib.py | MIT |
def align(self, imgDim, rgbImg, bb=None,
landmarks=None, landmarkIndices=INNER_EYES_AND_BOTTOM_LIP,
skipMulti=False, scale=1.0):
r"""align(imgDim, rgbImg, bb=None, landmarks=None, landmarkIndices=INNER_EYES_AND_BOTTOM_LIP)
Transform and align a face in an image.
:pa... | align(imgDim, rgbImg, bb=None, landmarks=None, landmarkIndices=INNER_EYES_AND_BOTTOM_LIP)
Transform and align a face in an image.
:param imgDim: The edge length in pixels of the square the image is resized to.
:type imgDim: int
:param rgbImg: RGB image to process. Shape: (height, width... | align | python | davidsandberg/facenet | tmp/align_dlib.py | https://github.com/davidsandberg/facenet/blob/master/tmp/align_dlib.py | MIT |
def tffunc(*argtypes):
'''Helper that transforms TF-graph generating function into a regular one.
See "resize" function below.
'''
placeholders = list(map(tf.placeholder, argtypes))
def wrap(f):
out = f(*placeholders)
def wrapper(*args, **kw):
... | Helper that transforms TF-graph generating function into a regular one.
See "resize" function below.
| tffunc | python | davidsandberg/facenet | tmp/deepdream.py | https://github.com/davidsandberg/facenet/blob/master/tmp/deepdream.py | MIT |
def calc_grad_tiled(img, t_grad, tile_size=512):
'''Compute the value of tensor t_grad over the image in a tiled way.
Random shifts are applied to the image to blur tile boundaries over
multiple iterations.'''
sz = tile_size
h, w = img.shape[:2]
sx, sy = np.random.randin... | Compute the value of tensor t_grad over the image in a tiled way.
Random shifts are applied to the image to blur tile boundaries over
multiple iterations. | calc_grad_tiled | python | davidsandberg/facenet | tmp/deepdream.py | https://github.com/davidsandberg/facenet/blob/master/tmp/deepdream.py | MIT |
def lap_split(img):
'''Split the image into lo and hi frequency components'''
with tf.name_scope('split'):
lo = tf.nn.conv2d(img, k5x5, [1,2,2,1], 'SAME')
lo2 = tf.nn.conv2d_transpose(lo, k5x5*4, tf.shape(img), [1,2,2,1])
hi = img-lo2
return lo, hi | Split the image into lo and hi frequency components | lap_split | python | davidsandberg/facenet | tmp/deepdream.py | https://github.com/davidsandberg/facenet/blob/master/tmp/deepdream.py | MIT |
def normalize_std(img, eps=1e-10):
'''Normalize image by making its standard deviation = 1.0'''
with tf.name_scope('normalize'):
std = tf.sqrt(tf.reduce_mean(tf.square(img)))
return img/tf.maximum(std, eps) | Normalize image by making its standard deviation = 1.0 | normalize_std | python | davidsandberg/facenet | tmp/deepdream.py | https://github.com/davidsandberg/facenet/blob/master/tmp/deepdream.py | MIT |
def data_type():
"""Return the type of the activations, weights, and placeholder variables."""
if FLAGS.use_fp16:
return tf.float16
else:
return tf.float32 | Return the type of the activations, weights, and placeholder variables. | data_type | python | davidsandberg/facenet | tmp/mnist_center_loss.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py | MIT |
def maybe_download(filename):
"""Download the data from Yann's website, unless it's already here."""
if not tf.gfile.Exists(WORK_DIRECTORY):
tf.gfile.MakeDirs(WORK_DIRECTORY)
filepath = os.path.join(WORK_DIRECTORY, filename)
if not tf.gfile.Exists(filepath):
filepath, _ = urllib.request.... | Download the data from Yann's website, unless it's already here. | maybe_download | python | davidsandberg/facenet | tmp/mnist_center_loss.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py | MIT |
def extract_data(filename, num_images):
"""Extract the images into a 4D tensor [image index, y, x, channels].
Values are rescaled from [0, 255] down to [-0.5, 0.5].
"""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
bytestream.read(16)
buf = bytestream.read(IMA... | Extract the images into a 4D tensor [image index, y, x, channels].
Values are rescaled from [0, 255] down to [-0.5, 0.5].
| extract_data | python | davidsandberg/facenet | tmp/mnist_center_loss.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py | MIT |
def extract_labels(filename, num_images):
"""Extract the labels into a vector of int64 label IDs."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
bytestream.read(8)
buf = bytestream.read(1 * num_images)
labels = np.frombuffer(buf, dtype=np.uint8).astype(np.in... | Extract the labels into a vector of int64 label IDs. | extract_labels | python | davidsandberg/facenet | tmp/mnist_center_loss.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py | MIT |
def fake_data(num_images):
"""Generate a fake dataset that matches the dimensions of MNIST."""
data = np.ndarray(
shape=(num_images, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS),
dtype=np.float32)
labels = np.zeros(shape=(num_images,), dtype=np.int64)
for image in range(num_images):
lab... | Generate a fake dataset that matches the dimensions of MNIST. | fake_data | python | davidsandberg/facenet | tmp/mnist_center_loss.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py | MIT |
def error_rate(predictions, labels):
"""Return the error rate based on dense predictions and sparse labels."""
return 100.0 - (
100.0 *
np.sum(np.argmax(predictions, 1) == labels) /
predictions.shape[0]) | Return the error rate based on dense predictions and sparse labels. | error_rate | python | davidsandberg/facenet | tmp/mnist_center_loss.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py | MIT |
def batch_norm(x, phase_train): #pylint: disable=unused-variable
"""
Batch normalization on convolutional maps.
Args:
x: Tensor, 4D BHWD input maps
n_out: integer, depth of input maps
phase_train: boolean tf.Variable, true indicates training p... |
Batch normalization on convolutional maps.
Args:
x: Tensor, 4D BHWD input maps
n_out: integer, depth of input maps
phase_train: boolean tf.Variable, true indicates training phase
scope: string, variable scope
affn: w... | batch_norm | python | davidsandberg/facenet | tmp/mnist_center_loss.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py | MIT |
def eval_in_batches(data, sess):
"""Get all predictions for a dataset by running it in small batches."""
size = data.shape[0]
if size < EVAL_BATCH_SIZE:
raise ValueError("batch size for evals larger than dataset: %d" % size)
predictions = np.ndarray(shape=(size, NUM_LABELS), ... | Get all predictions for a dataset by running it in small batches. | eval_in_batches | python | davidsandberg/facenet | tmp/mnist_center_loss.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py | MIT |
def calculate_embeddings(data, sess):
"""Get all predictions for a dataset by running it in small batches."""
size = data.shape[0]
if size < EVAL_BATCH_SIZE:
raise ValueError("batch size for evals larger than dataset: %d" % size)
predictions = np.ndarray(shape=(size, 2), dtyp... | Get all predictions for a dataset by running it in small batches. | calculate_embeddings | python | davidsandberg/facenet | tmp/mnist_center_loss.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_center_loss.py | MIT |
def data_type():
"""Return the type of the activations, weights, and placeholder variables."""
if FLAGS.use_fp16:
return tf.float16
else:
return tf.float32 | Return the type of the activations, weights, and placeholder variables. | data_type | python | davidsandberg/facenet | tmp/mnist_noise_labels.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_noise_labels.py | MIT |
def maybe_download(filename):
"""Download the data from Yann's website, unless it's already here."""
if not tf.gfile.Exists(WORK_DIRECTORY):
tf.gfile.MakeDirs(WORK_DIRECTORY)
filepath = os.path.join(WORK_DIRECTORY, filename)
if not tf.gfile.Exists(filepath):
filepath, _ = urllib.request.... | Download the data from Yann's website, unless it's already here. | maybe_download | python | davidsandberg/facenet | tmp/mnist_noise_labels.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_noise_labels.py | MIT |
def extract_data(filename, num_images):
"""Extract the images into a 4D tensor [image index, y, x, channels].
Values are rescaled from [0, 255] down to [-0.5, 0.5].
"""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
bytestream.read(16)
buf = bytestream.read(IMA... | Extract the images into a 4D tensor [image index, y, x, channels].
Values are rescaled from [0, 255] down to [-0.5, 0.5].
| extract_data | python | davidsandberg/facenet | tmp/mnist_noise_labels.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_noise_labels.py | MIT |
def extract_labels(filename, num_images):
"""Extract the labels into a vector of int64 label IDs."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
bytestream.read(8)
buf = bytestream.read(1 * num_images)
labels = np.frombuffer(buf, dtype=np.uint8).astype(np.in... | Extract the labels into a vector of int64 label IDs. | extract_labels | python | davidsandberg/facenet | tmp/mnist_noise_labels.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_noise_labels.py | MIT |
def fake_data(num_images):
"""Generate a fake dataset that matches the dimensions of MNIST."""
data = np.ndarray(
shape=(num_images, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNELS),
dtype=np.float32)
labels = np.zeros(shape=(num_images,), dtype=np.int64)
for image in range(num_images):
lab... | Generate a fake dataset that matches the dimensions of MNIST. | fake_data | python | davidsandberg/facenet | tmp/mnist_noise_labels.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_noise_labels.py | MIT |
def error_rate(predictions, labels):
"""Return the error rate based on dense predictions and sparse labels."""
return 100.0 - (
100.0 *
np.sum(np.argmax(predictions, 1) == labels) /
predictions.shape[0]) | Return the error rate based on dense predictions and sparse labels. | error_rate | python | davidsandberg/facenet | tmp/mnist_noise_labels.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_noise_labels.py | MIT |
def eval_in_batches(data, sess):
"""Get all predictions for a dataset by running it in small batches."""
size = data.shape[0]
if size < EVAL_BATCH_SIZE:
raise ValueError("batch size for evals larger than dataset: %d" % size)
predictions = np.ndarray(shape=(size, NUM_LABELS), ... | Get all predictions for a dataset by running it in small batches. | eval_in_batches | python | davidsandberg/facenet | tmp/mnist_noise_labels.py | https://github.com/davidsandberg/facenet/blob/master/tmp/mnist_noise_labels.py | MIT |
def l2_loss(tensor, weight=1.0, scope=None):
"""Define a L2Loss, useful for regularize, i.e. weight decay.
Args:
tensor: tensor to regularize.
weight: an optional weight to modulate the loss.
scope: Optional scope for op_scope.
Returns:
the L2 loss op.
"""
with tf.name_scope(... | Define a L2Loss, useful for regularize, i.e. weight decay.
Args:
tensor: tensor to regularize.
weight: an optional weight to modulate the loss.
scope: Optional scope for op_scope.
Returns:
the L2 loss op.
| l2_loss | python | davidsandberg/facenet | tmp/network.py | https://github.com/davidsandberg/facenet/blob/master/tmp/network.py | MIT |
def batch_norm(x, phase_train):
"""
Batch normalization on convolutional maps.
Args:
x: Tensor, 4D BHWD input maps
n_out: integer, depth of input maps
phase_train: boolean tf.Variable, true indicates training phase
scope: string, variable scope
a... |
Batch normalization on convolutional maps.
Args:
x: Tensor, 4D BHWD input maps
n_out: integer, depth of input maps
phase_train: boolean tf.Variable, true indicates training phase
scope: string, variable scope
affn: whether to affn-transform out... | batch_norm | python | davidsandberg/facenet | tmp/network.py | https://github.com/davidsandberg/facenet/blob/master/tmp/network.py | MIT |
def inference(images, keep_probability, phase_train=True, weight_decay=0.0):
""" Define an inference network for face recognition based
on inception modules using batch normalization
Args:
images: The images to run inference on, dimensions batch_size x height x width x channels
phas... | Define an inference network for face recognition based
on inception modules using batch normalization
Args:
images: The images to run inference on, dimensions batch_size x height x width x channels
phase_train: True if batch normalization should operate in training mode
| inference | python | davidsandberg/facenet | tmp/nn2.py | https://github.com/davidsandberg/facenet/blob/master/tmp/nn2.py | MIT |
def inference(images, keep_probability, phase_train=True, weight_decay=0.0):
""" Define an inference network for face recognition based
on inception modules using batch normalization
Args:
images: The images to run inference on, dimensions batch_size x height x width x channels
phas... | Define an inference network for face recognition based
on inception modules using batch normalization
Args:
images: The images to run inference on, dimensions batch_size x height x width x channels
phase_train: True if batch normalization should operate in training mode
| inference | python | davidsandberg/facenet | tmp/nn3.py | https://github.com/davidsandberg/facenet/blob/master/tmp/nn3.py | MIT |
def inference(images, keep_probability, phase_train=True, weight_decay=0.0):
""" Define an inference network for face recognition based
on inception modules using batch normalization
Args:
images: The images to run inference on, dimensions batch_size x height x width x channels
phas... | Define an inference network for face recognition based
on inception modules using batch normalization
Args:
images: The images to run inference on, dimensions batch_size x height x width x channels
phase_train: True if batch normalization should operate in training mode
| inference | python | davidsandberg/facenet | tmp/nn4.py | https://github.com/davidsandberg/facenet/blob/master/tmp/nn4.py | MIT |
def inference(images, keep_probability, phase_train=True, weight_decay=0.0):
""" Define an inference network for face recognition based
on inception modules using batch normalization
Args:
images: The images to run inference on, dimensions batch_size x height x width x channels
phas... | Define an inference network for face recognition based
on inception modules using batch normalization
Args:
images: The images to run inference on, dimensions batch_size x height x width x channels
phase_train: True if batch normalization should operate in training mode
| inference | python | davidsandberg/facenet | tmp/nn4_small2_v1.py | https://github.com/davidsandberg/facenet/blob/master/tmp/nn4_small2_v1.py | MIT |
def gradients(ys, xs, grad_ys=None, checkpoints='collection', **kwargs):
'''
Authors: Tim Salimans & Yaroslav Bulatov
memory efficient gradient implementation inspired by "Training Deep Nets with Sublinear Memory Cost"
by Chen et al. 2016 (https://arxiv.org/abs/1604.06174)
ys,xs,grad_ys,kwargs are... |
Authors: Tim Salimans & Yaroslav Bulatov
memory efficient gradient implementation inspired by "Training Deep Nets with Sublinear Memory Cost"
by Chen et al. 2016 (https://arxiv.org/abs/1604.06174)
ys,xs,grad_ys,kwargs are the arguments to standard tensorflow tf.gradients
(https://www.tensorflow.o... | gradients | python | openai/glow | memory_saving_gradients.py | https://github.com/openai/glow/blob/master/memory_saving_gradients.py | MIT |
def capture_ops():
"""Decorator to capture ops created in the block.
with capture_ops() as ops:
# create some ops
print(ops) # => prints ops created.
"""
micros = int(time.time()*10**6)
scope_name = str(micros)
op_list = []
with tf.name_scope(scope_name):
yield op_list
... | Decorator to capture ops created in the block.
with capture_ops() as ops:
# create some ops
print(ops) # => prints ops created.
| capture_ops | python | openai/glow | memory_saving_gradients.py | https://github.com/openai/glow/blob/master/memory_saving_gradients.py | MIT |
def debug_print(s, *args):
"""Like logger.log, but also replaces all TensorFlow ops/tensors with their
names. Sensitive to value of DEBUG_LOGGING, see enable_debug/disable_debug
Usage:
debug_print("see tensors %s for %s", tensorlist, [1,2,3])
"""
if DEBUG_LOGGING:
formatted_args = [f... | Like logger.log, but also replaces all TensorFlow ops/tensors with their
names. Sensitive to value of DEBUG_LOGGING, see enable_debug/disable_debug
Usage:
debug_print("see tensors %s for %s", tensorlist, [1,2,3])
| debug_print | python | openai/glow | memory_saving_gradients.py | https://github.com/openai/glow/blob/master/memory_saving_gradients.py | MIT |
def format_ops(ops, sort_outputs=True):
"""Helper method for printing ops. Converts Tensor/Operation op to op.name,
rest to str(op)."""
if hasattr(ops, '__iter__') and not isinstance(ops, str):
l = [(op.name if hasattr(op, "name") else str(op)) for op in ops]
if sort_outputs:
re... | Helper method for printing ops. Converts Tensor/Operation op to op.name,
rest to str(op). | format_ops | python | openai/glow | memory_saving_gradients.py | https://github.com/openai/glow/blob/master/memory_saving_gradients.py | MIT |
def _symmetric_matrix_square_root(mat, eps=1e-10):
"""Compute square root of a symmetric matrix.
Note that this is different from an elementwise square root. We want to
compute M' where M' = sqrt(mat) such that M' * M' = mat.
Also note that this method **only** works for symmetric matrices.
Args:
... | Compute square root of a symmetric matrix.
Note that this is different from an elementwise square root. We want to
compute M' where M' = sqrt(mat) such that M' * M' = mat.
Also note that this method **only** works for symmetric matrices.
Args:
mat: Matrix to take the square root of.
eps: Sma... | _symmetric_matrix_square_root | python | openai/glow | tfops.py | https://github.com/openai/glow/blob/master/tfops.py | MIT |
def forward(self, x: Tensor, edge_index: Adj,
edge_attr: OptTensor = None, batch: Adj = None,
angle_data: List = None, size: Size = None) -> Tensor:
""" Inputs:
* x: (n_points, d) where d is pos_dims + feat_dims
* edge_index: (2, n_edges)
* ... | Inputs:
* x: (n_points, d) where d is pos_dims + feat_dims
* edge_index: (2, n_edges)
* edge_attr: tensor (n_edges, n_feats) excluding basic distance feats.
* batch: (n_points,) long tensor. specifies xloud belonging for each point
* angle_data: list of tens... | forward | python | lucidrains/egnn-pytorch | egnn_pytorch/egnn_pytorch_geometric.py | https://github.com/lucidrains/egnn-pytorch/blob/master/egnn_pytorch/egnn_pytorch_geometric.py | MIT |
def make_jobfile_from_command_list(jobfile_path, commands):
"""
Save a jobfile containing commands to run.
Parameters
----------
jobfile_path : str or path
commands : list of str
"""
# Creating a jobfile containing all commands to run
jobfile_content = ''.join('%s\n' % com for com in... |
Save a jobfile containing commands to run.
Parameters
----------
jobfile_path : str or path
commands : list of str
| make_jobfile_from_command_list | python | WassimTenachi/PhySO | benchmarking/utils.py | https://github.com/WassimTenachi/PhySO/blob/master/benchmarking/utils.py | MIT |
def assess_equivalence (pareto_df, Feynman_pb, check_only_most_acc = False, verbose = False):
"""
Checks if at least one expression in the Pareto front is symbolically equivalent to target expression, following a
similar methodology as SRBench (see https://github.com/cavalab/srbench).
I.e, an expression... |
Checks if at least one expression in the Pareto front is symbolically equivalent to target expression, following a
similar methodology as SRBench (see https://github.com/cavalab/srbench).
I.e, an expression is deemed equivalent if:
- the symbolic difference simplifies to 0
- OR the symbolic... | assess_equivalence | python | WassimTenachi/PhySO | benchmarking/FeynmanBenchmark/feynman_results_analysis.py | https://github.com/WassimTenachi/PhySO/blob/master/benchmarking/FeynmanBenchmark/feynman_results_analysis.py | MIT |
def assess_metric_test (pareto_df, Feynman_pb, metric_func, i_pareto=-1):
"""
Computes metric value of the best Pareto front expression on noiseless test data.
Parameters
----------
pareto_df : pd.DataFrame
Pareto front dataframe generated by PhySO.
Feynman_pb : physo.benchmark.FeynmanDa... |
Computes metric value of the best Pareto front expression on noiseless test data.
Parameters
----------
pareto_df : pd.DataFrame
Pareto front dataframe generated by PhySO.
Feynman_pb : physo.benchmark.FeynmanDataset.FeynmanProblem.FeynmanProblem
Related Feynman problem.
metric_f... | assess_metric_test | python | WassimTenachi/PhySO | benchmarking/FeynmanBenchmark/feynman_results_analysis.py | https://github.com/WassimTenachi/PhySO/blob/master/benchmarking/FeynmanBenchmark/feynman_results_analysis.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.