input
string
label
int64
category
string
sample_id
string
attention_cache = PagedAttentionCache( self.model.config, self.generation_config, self.model.device, self.model.dtype, tp_size=getattr(self.model, "_tp_size", None), # Use model's actual TP setting allow_block_sharing=self....
0
function_complex
huggingface/transformers:src/transformers/generation/continuous_batching/continuous_api.py:ContinuousBatchingManager._run_generation_loop
_slider_to_be_ready(app) reset_button = app.get_by_test_id("stButton").filter(has_text="Reset Height") expect(reset_button).to_be_visible() _expect_pdf_container_attached(app) # Wait for PDF to be fully loaded _wait_for_pdf_to_load(app) # Take snapshot of just the PDF container in initial st...
1
test
streamlit/streamlit:e2e_playwright/custom_components/pdf_component_test.py:test_st_pdf_interactive
self, groq_messages, output_format: type[T], schema) -> ChatCompletion: """Handle structured output using tool calling.""" tool = ChatCompletionToolParam( function={ 'name': output_format.__name__, 'description': f'Extract information in the format of {output_format.__name__}', 'parameters': schema, ...
0
function_simple
browser-use/browser-use:browser_use/llm/groq/chat.py:ChatGroq._invoke_with_tool_calling
_sliding_window(self): EXPECTED_TEXT_COMPLETION = " This is a nice place. I really enjoy the scenery, and the atmosphere is so relaxing. I'm grateful for the opportunity to experience this place. It" tokenizer = AutoTokenizer.from_pretrained(self.TEST_MODEL_ID) prompt = "This is a nice place. " ...
0
test
huggingface/transformers:tests/models/exaone4/test_modeling_exaone4.py:Exaone4IntegrationTest.test_model_generation_beyond_sliding_window
config = self.get_text_config() model = Qwen3VLTextModel(config).to(torch_device).eval() batch_size, seq_len = 2, 8 input_ids = ids_tensor([batch_size, seq_len], config.vocab_size).to(torch_device) position_ids_2d = torch.arange(seq_len, device=torch_device).unsqueeze(0).expand(batch...
0
test
huggingface/transformers:tests/models/qwen3_vl/test_modeling_qwen3_vl.py:Qwen3VLTextModelPositionIdsTest.test_2d_position_ids_forward
(stmt, ast.Return) and isinstance(stmt.value, ast.List): backends: list[str] = [] for e in stmt.value.elts: if isinstance(e, ast.Attribute): backends.append(e.attr) elif ( isinstance(e, ast.Starred) and i...
1
function_complex
vllm-project/vllm:tools/pre_commit/generate_attention_backend_docs.py:_get_backends_from_return
tex]) # Create mock run response run_response = Mock() result_data = Mock() result_data.component_id = "output-123" result_data.outputs = {"message": {"message": "Hello World"}} result_data.metadata = {} run_output = Mock() run_output.outputs = [result_d...
1
test
langflow-ai/langflow:src/backend/tests/unit/api/v2/test_converters.py:TestRunResponseToWorkflowResponse.test_run_response_basic_output_node
- Events are tuples of (event_id, value, put_time) - Breaks the loop when receiving a None value, signaling completion - Tracks and logs timing metrics for queue time and client processing time - Notifies client consumption via client_consumed_queue """ while True: event...
1
function_simple
langflow-ai/langflow:src/lfx/src/lfx/cli/serve_app.py:consume_and_yield
if not test_cases: EvaluationRun.update( status="FAILED", complete_time=current_timestamp() ).where(EvaluationRun.id == run_id).execute() return # Execute each test case results = [] for c...
1
function_complex
infiniflow/ragflow:api/db/services/evaluation_service.py:EvaluationService._execute_evaluation
", port=5432, diskann=False, hnsw=False, minconn=1, maxconn=4, connection_pool=explicit_pool ) # Verify the _get_cursor context manager was called mock_get_cursor.assert_called() mock_connection_pool.assert_not_cal...
1
test
mem0ai/mem0:tests/vector_stores/test_pgvector.py:TestPGVector.test_create_col_psycopg3_with_explicit_pool
of file raises exit code 1.""" directory = tmp_path / "test_dir" directory.mkdir() with pytest.raises(typer.Exit) as exc_info: run( script_path=directory, input_value=None, input_value_option=None, verbose=False, ...
1
test
langflow-ai/langflow:src/lfx/tests/unit/cli/test_run_command.py:TestRunCommand.test_execute_directory_instead_of_file
.get(signal.wait.remote()) ray.get(captured_id) # noqa: F821 signal = SignalActor.remote() obj_ref = f.remote(signal) # Delete local references. del f del captured_id # Test that the captured object ref is pinned despite having no local # references. ray.get(signal.send.remot...
0
test
ray-project/ray:python/ray/tests/test_reference_counting_standalone.py:test_captured_object_ref
tool_choice: str | dict, enable_thinking: bool, ): if not stream: # Non-streaming test chat_completion = await client.chat.completions.create( messages=messages, model=model_name, tools=tools, tool_choice=tool_choice, extra_body={"ch...
1
test
vllm-project/vllm:tests/entrypoints/openai/test_completion_with_function_calling.py:test_function_tool_use
""" Apply rotary embeddings to input tensors using the given frequency tensor. This function applies rotary embeddings to the given query or key 'x' tensors using the provided frequency tensor 'freqs_cis'. The input tensors are reshaped as complex numbers, and the frequency tensor is reshap...
1
function_simple
Comfy-Org/ComfyUI:comfy/ldm/ace/attention.py:CustomLiteLAProcessor2_0.apply_rotary_emb
).to(torch_device) with torch.no_grad(): outputs = self.model(**inputs) self.assertEqual(outputs.iou_scores.shape, (1, 1, 3)) self.assertEqual(outputs.pred_masks.shape, (1, 1, 3, 256, 256)) sorted_indices = torch.argsort(outputs.iou_scores.squeeze(), descending=True) ...
0
test
huggingface/transformers:tests/models/sam2/test_modeling_sam2.py:Sam2ModelIntegrationTest.test_inference_mask_generation_one_point_multimask
The temporal, height and width of feature shape of each image in LLM. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *opt...
0
function_simple
huggingface/transformers:src/transformers/models/glm4v/modular_glm4v.py:Glm4vModel.forward
client: AsyncClient, created_api_key, mock_settings_dev_api_enabled, # noqa: ARG002 ): """Test POST /workflow/stop handles already cancelled jobs.""" job_id = str(uuid4()) mock_job = MagicMock() mock_job.job_id = job_id mock_job.status = JobStatus.CANCELL...
1
test
langflow-ai/langflow:src/backend/tests/unit/api/v2/test_workflow.py:TestWorkflowStop.test_stop_workflow_already_cancelled
.ProfilerActivity.CUDA) elif self.device_type == "xpu": activities.append(torch.profiler.ProfilerActivity.XPU) profiler = torch.profiler.profile( activities=activities, record_shapes=True, ) with profiler as prof: _ = self.model.generate( ...
0
function_simple
huggingface/transformers:benchmark_v2/framework/benchmark_runner.py:BenchmarkRunner.profile_generate
Python:", max_tokens=30, temperature=0, stream=True, echo=False, logprobs=1, extra_body={"return_token_ids": True, "return_tokens_as_token_ids": True}, ) # Collect streamed tokens streamed_prompt_token_ids = [] str...
1
test
vllm-project/vllm:tests/entrypoints/openai/test_return_token_ids.py:test_comparison_with_prompt_logprobs_and_logprobs
Args: content_type: MIME type of the video. Returns: Bedrock format string or None if unsupported. """ format_map = { "video/mp4": "mp4", "video/quicktime": "mov", "video/x-matroska": "mkv", "video/webm": "webm", ...
0
function_simple
crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/bedrock/completion.py:BedrockCompletion._get_video_format
api_key (str): Your Firecrawl API key. config (dict): Optional. It contains Firecrawl v2 API parameters. Default configuration options (Firecrawl v2 API): formats (list[str]): Content formats to return. Default: ["markdown"] only_main_content (bool): Only return main content excluding headers, navs, f...
0
documentation
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/firecrawl_scrape_website_tool/firecrawl_scrape_website_tool.py:FirecrawlScrapeWebsiteTool:class_doc
]: url = grpc_url if _do_request == self._do_grpc_request else http_url num_requests = 5 with ThreadPoolExecutor(num_requests + 5) as tpe: # Submit `max_ongoing_requests` blocking requests. futures = [tpe.submit(_do_request, url) for _ in range(num_req...
0
test
ray-project/ray:python/ray/serve/tests/test_direct_ingress.py:TestDirectIngressBackpressure.test_max_ongoing_requests
def test_model_generation_long_flash(self): EXPECTED_OUTPUT_TOKEN_IDS = [433, 9055] input_ids = [433, 9055] * 2048 model = Exaone4ForCausalLM.from_pretrained( self.TEST_MODEL_ID, device_map="auto", dtype=torch.bfloat16, attn_implementation="flash_attention_2" ) input_...
0
test
huggingface/transformers:tests/models/exaone4/test_modeling_exaone4.py:Exaone4IntegrationTest.test_model_generation_long_flash
-> tqdm.tqdm: """Create a styled progress bar for downloads. Args: total_size: Total size in bytes. url: The URL being downloaded. ncols: Number of columns for the progress bar. max_url_length: Maximum length to show for the URL. Returns: A configured tqdm progress bar. """ # Truncate U...
1
function_complex
google/langextract:langextract/progress.py:create_download_progress_bar
# Check for type changes if self._has_type_change(call) and phase != MigrationPhase.CONTRACT: violations.append( Violation("DIRECT_TYPE_CHANGE", "Type changes should use expand-contract pattern", call.lineno) ) # Check for nullable changes if se...
1
function_simple
langflow-ai/langflow:src/backend/base/langflow/alembic/migration_validator.py:MigrationValidator._check_alter_column
Optional["SettingsService"], ) -> tuple[dict[str, Any], str]: """Load components in production mode with fallback chain. Tries: index -> cache -> dynamic build (with caching) Args: settings_service: Settings service for custom index path Returns: Tuple of (modules_dict, index_source)...
1
function_simple
langflow-ai/langflow:src/lfx/src/lfx/interface/components.py:_load_production_mode
.return_value = "Async result" def guardrail_fn(output: TaskOutput) -> tuple[bool, str]: return False, "Always fails" task = Task( description="Test task", expected_output="Test output", agent=test_agent, guardrail=guardrail_fn, g...
0
test
crewAIInc/crewAI:lib/crewai/tests/task/test_async_task.py:TestAsyncGuardrails.test_ainvoke_guardrail_max_retries_exceeded
) row = cursor.fetchone() conn.close() if row: return WorkflowStats( workflow_id=row[0], total_ratings=row[1], average_rating=row[2], total_reviews=row[3], total_views=row[4], total_...
0
function_simple
Zie619/n8n-workflows:src/community_features.py:CommunityFeatures.get_workflow_stats
{k: f'"{v}"' if not is_number(v) else v for k, v in generate_flags_as_dict.items()} # 2. c. [no processing needed] lists are lists of ints because `generate` doesn't take lists of strings :) # We also mention in the help message that we only accept lists of ints for now. # 3. Join the result into a comma ...
0
function_simple
huggingface/transformers:src/transformers/cli/chat.py:parse_generate_flags
"""Create a new podcast in the database.""" try: content_json = json.dumps(content) sources_json = json.dumps(sources) if sources else None current_time = datetime.now().isoformat() query = """ INSERT INTO podcasts (title, date, con...
0
function_simple
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/podcast_service.py:PodcastService.create_podcast
out parameters with no gradients parameters = [p for p in parameters if p.grad is not None] assert len(parameters) > 0, "No parameters with gradients found" # Calculate total norm if norm_type == float("inf"): total_norm = max(p.grad.detach().abs().max() for p in parameters) else: ...
0
function_complex
huggingface/transformers:examples/3D_parallel.py:clip_grad_norm_
KV cache slices from a given attention layer tensor. This function handles multiple backend layouts: - MLA (Multi-Linear Attention) or FlashInfer: KV tensors are indexed along the first dimension. - FlashAttention: KV tensors are indexed along the second ...
1
function_complex
vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_connector.py:P2pNcclConnector.save_kv_layer
been set before any value is" "added") if self.datatype is list: if not isinstance(value, (str, list)): raise ValueError(f"[{self._name}] List values should be set as a Str or List. Got " f"{type(value)} ({value})") ...
1
function_complex
deepfakes/faceswap:lib/config/objects.py:ConfigItem.set
_version = torch.version.cuda # e.g. "13.0" or "12.8" if cuda_version: system_cuda_display = cuda_version system_cuda_tag = cuda_version.replace(".", "")[:3] # "130" or "128" except Exception: pass if system_cuda_tag is None or system_cuda_tag.startswith(wanted_cuda): ...
0
function_complex
unslothai/unsloth:unsloth/import_fixes.py:_get_vllm_cuda_mismatch_message
reorder_cache(self, beam_idx: torch.LongTensor): """Reorders the cache for beam search, given the selected beam indices.""" for layer_idx in range(len(self.key_cache)): if self.key_cache[layer_idx] is not None: device = self.key_cache[layer_idx].device beam_i...
0
function_simple
huggingface/transformers:src/transformers/models/qwen3_next/modular_qwen3_next.py:Qwen3NextDynamicCache.reorder_cache
""" \\documentclass{article} \\begin{document} Some text. \\begin{thebibliography}{9} \\bibitem{ref1} Author One, Title One, 2020. \\bibitem{ref2} Author Two, Title Two, 2021. \\end{thebibliography} \\end{document} """ in_doc = InputDocument( path_or_stream=BytesIO(latex_...
1
test
docling-project/docling:tests/test_backend_latex.py:test_latex_bibliography
default_profiler_config.delay_iterations = 2 default_profiler_config.max_iterations = 2 profiler = ConcreteWorkerProfiler(default_profiler_config) profiler.start() # Step 1 profiler.step() assert profiler._running is False assert profiler._active is True # Step 2 (Starts now) pro...
1
test
vllm-project/vllm:tests/v1/worker/test_gpu_profiler.py:test_delayed_start_and_max_iters
] else: assert len(images) == len(prompts), "Number of images must match number of prompts" messages = [ [ { "role": "system", "content": [{"type": "text", "text": system_message}], }, ] ...
1
function_complex
huggingface/diffusers:src/diffusers/pipelines/flux2/pipeline_flux2.py:format_input
] = [] strategy2 = BFSDeepCrawlStrategy( max_depth=2, max_pages=10, resume_state=last_state, ) mock_crawler2 = create_mock_crawler_tracking(crawled_in_resume, return_no_links=True) await strategy2._arun_batch("https://example.com", mock_crawler2, mo...
1
test
unclecode/crawl4ai:tests/deep_crawling/test_deep_crawl_resume.py:TestBFSResume.test_simulated_crash_mid_crawl
prompt_cross_attn( query=normed_hidden_states, key=prompt_features, value=prompt_features, attention_mask=cross_attn_mask, **kwargs, ) encoder_hidden_states = residual + self.prompt_cross_attn_dropout(attn_output) ...
0
function_simple
huggingface/transformers:src/transformers/models/sam3/modeling_sam3.py:Sam3MaskDecoder.forward
description="Say hello", expected_output="hello", agent=agent, ) crew = Crew( agents=[agent], tasks=[task], share_crew=True, ) result = crew.kickoff() assert crew._execu...
0
test
crewAIInc/crewAI:lib/crewai/tests/telemetry/test_flow_crew_span_integration.py:test_crew_execution_span_in_async_flow
) torch.testing.assert_close( outputs.pred_masks[:, :, :, :2, :2], torch.tensor( [ [[[[-19.1423, -21.6488], [-17.8018, -22.6512]]], [[[-7.1591, -9.8201], [-7.4133, -9.2781]]]], [[[[-16.7645, -15.2790], [-16.1805, -16.2937]]...
0
test
huggingface/transformers:tests/models/edgetam/test_modeling_edgetam.py:EdgeTamModelIntegrationTest.test_inference_mask_generation_batched_images_batched_points_multi_points
# Add debugging port debug_port = self._find_free_port() launch_args.extend( [ f'--remote-debugging-port={debug_port}', ] ) assert '--user-data-dir' in str(launch_args), ( 'User data dir must be set somewhere in launch args to a non-default path, otherwise Chrome will not let us at...
0
function_complex
browser-use/browser-use:browser_use/browser/watchdogs/local_browser_watchdog.py:LocalBrowserWatchdog._launch_browser
max_tokens=100, messages=[ClaudeMessage(role="user", content="Hello")], temperature=0.7, top_p=0.9, top_k=40, stop_sequences=["STOP", "END"], stream=True, ) params = claude_request_to_text_generation(request) a...
0
test
exo-explore/exo:src/exo/master/tests/test_claude_api.py:TestClaudeRequestToInternal.test_request_with_optional_parameters
en(1) occupied_ports.append(sock) """Test that multiple replicas on the same node occupy unique ports.""" serve._run( Hybrid.options(name="default-deployment").bind(message="Hello world!"), _blocking=False, ) # check that the deployment failed def _func(): serve_det...
0
test
ray-project/ray:python/ray/serve/tests/test_direct_ingress.py:test_no_port_available
""" Process and output the audio. Args: *args: Can take any positional argument. **kwargs: Can take any keyword argument. Returns: out (Any): This function can return any output. """ stream = await asyncio.to_thread( pya.ope...
1
function_simple
run-llama/llama_index:llama-index-integrations/voice_agents/llama-index-voice-agents-gemini-live/llama_index/voice_agents/gemini_live/audio_interface.py:GeminiLiveVoiceAgentInterface.output
# Add current metadata to buffer, if buffer is full, drop the oldest entry if len(self._buffer) >= self._buffer_maxlen: # Record the number of dropped attempts oldest_entry = self._buffer.popleft() self._metric_recorder.set_metric_...
0
function_complex
ray-project/ray:python/ray/dashboard/modules/aggregator/task_events_metadata_buffer.py:TaskEventsMetadataBuffer.merge
existing = _DummyMCPServer(id="mcp-1", name="srv", url="http://server", server_type="sse", tenant_id="tenant_1", variables={}, headers={}) _set_request_json(monkeypatch, module, {"mcp_id": "mcp-1"}) monkeypatch.setattr(module.MCPServerService, "get_by_id", lambda _mcp_id: (False, None)) res = _run(modul...
1
test
infiniflow/ragflow:test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py:test_update_validation_guards
source="sitemap", pattern="*beautiful-soup*", extract_head=True # Get the metadata! )) print(f"\n📚 Found {len(soup_urls)} Beautiful Soup articles:\n") ...
1
function_simple
unclecode/crawl4ai:docs/examples/url_seeder/url_seeder_quick_demo.py:explore_beautifulsoup
self.assertEqual(preprocess_parameter_names, valid_processor_keys) is_tested = True # validation done by @filter_out_non_signature_kwargs decorator if hasattr(image_processor.preprocess, "_filter_out_non_signature_kwargs"): if hasattr(self.image_processor_tes...
0
test
huggingface/transformers:tests/models/phi4_multimodal/test_image_processing_phi4_multimodal.py:Phi4MultimodalImageProcessingTest.test_image_processor_preprocess_arguments
VitPoseForPoseEstimation model outputs. boxes (`list[list[list[float]]]` or `np.ndarray`): List or array of bounding boxes for each image. Each box should be a list of 4 floats representing the bounding box coordinates in COCO format (top_left_x, top_left_y, width, hei...
0
function_complex
huggingface/transformers:src/transformers/models/vitpose/image_processing_vitpose_fast.py:VitPoseImageProcessorFast.post_process_pose_estimation
_item = NewsItem( title=title, source_id=source_id, source_name=source_name, rank=rank, url=url, mobile_url=mobile_url, crawl_time=crawl_time, ranks=ranks, first_time=crawl_tim...
1
function_complex
sansan0/TrendRadar:trendradar/storage/base.py:convert_crawl_results_to_news_data
input_ids = inputs_dict["input_ids"] def _prepare_image_embeds_position_mask(input_ids, pad_size): image_embeds_position_mask = torch.zeros( input_ids.shape[0], input_ids.shape[1] + pad_size, device=torch_device, dtype=input_ids.dtype ) image_embeds_posi...
0
test
huggingface/transformers:tests/models/kosmos2_5/test_modeling_kosmos2_5.py:Kosmos2_5ModelTest.test_left_padding_compatibility
Code and formula extraction stage using the new runtime system. This stage uses the unified VLM runtime interface to extract code and formulas from document elements. It supports all runtime types (Transformers, MLX, API, etc.) through the runtime factory. The stage: 1. Filters code and formula elements 2. Uses the r...
1
documentation
docling-project/docling:docling/models/stages/code_formula/code_formula_vlm_model.py:CodeFormulaVlmModel:class_doc
shape(resized_images, disable_grouping=disable_grouping) processed_images_grouped = {} for shape, stacked_images in grouped_images.items(): # Fused rescale and normalize stacked_images = self.rescale_and_normalize( stacked_images, do_rescale, rescale_factor, do_n...
0
function_complex
huggingface/transformers:src/transformers/models/vilt/image_processing_vilt_fast.py:ViltImageProcessorFast._preprocess
"""Test different return types (pt, np, list).""" processor = self.get_processor() image = self.prepare_image_inputs() text_with_image = f"{self.image_token} Test image." text_only = "Test without image." # Test PyTorch tensors (with images - fast image processor only supports ...
0
test
huggingface/transformers:tests/models/lighton_ocr/test_processor_lighton_ocr.py:LightOnOcrProcessorTest.test_processor_return_types
async def test_trigger_run_bad(self, mocker): mocker.patch.object(KafkaConsumerHook, "get_consumer", return_value=MockedConsumer) trigger = KafkaMessageQueueTrigger( kafka_config_id="kafka_d", apply_function="unit.apache.kafka.triggers.test_msg_queue.apply_function_false", ...
1
test
apache/airflow:providers/apache/kafka/tests/unit/apache/kafka/triggers/test_msg_queue.py:TestMessageQueueTrigger.test_trigger_run_bad
日期字符串列表(YYYY-MM-DD 格式) """ dates = [] try: paginator = self.s3_client.get_paginator('list_objects_v2') pages = paginator.paginate(Bucket=self.bucket_name, Prefix="news/") for page in pages: if 'Contents' not in page: ...
1
function_complex
sansan0/TrendRadar:trendradar/storage/remote.py:RemoteStorageBackend.list_remote_dates
a_shape = w_shape # Same as weight shape for alignment # Determine weight dtype if weight_bits == 4: weight_dtype = "int4" elif weight_bits == 8: weight_dtype = torch.int8 else: raise ValueError(f"Unsupported weight_bits: {weight_bits}") return FusedMoEQuantConfig( ...
1
function_simple
vllm-project/vllm:vllm/model_executor/layers/fused_moe/config.py:awq_marlin_moe_quant_config
_tokens] (P/W/H/T positions with multimodal inputs) query: [num_tokens, num_heads * head_size] key: [num_tokens, num_kv_heads * head_size] """ assert positions.ndim == 2 assert key is not None num_tokens = positions.shape[-1] cos_sin = self.cos_sin_cache[...
1
function_simple
vllm-project/vllm:vllm/model_executor/layers/rotary_embedding/xdrope.py:XDRotaryEmbedding.forward_cuda
2, equal=False, data_context=DataContext.get_current(), locality_hints=["node1", "node2"], ) def get_fake_loc(item): assert isinstance(item, int), item if item in [0, 1, 4, 5, 8]: return "node1" else: return "node2" def get_bundle...
0
test
ray-project/ray:python/ray/data/tests/test_output_splitter.py:test_split_operator_locality_hints
. """ flash_attn_varlen_func = lazy_import_paged_flash_attention(module.config._attn_implementation) sliding_window = (-1, -1) if not getattr(module, "sliding_window", False) else (module.sliding_window - 1, 0) layer_type = "full_attention" if sliding_window == (-1, -1) else "sliding_attention" # ...
0
function_complex
huggingface/transformers:src/transformers/integrations/flash_paged.py:paged_attention_forward
score = torch.randn((m, e), device="cuda", dtype=dtype) topk_weights, topk_ids, _ = fused_topk(a, score, topk, renormalize=False) a1_gs = torch.ones((e,), device="cuda", dtype=torch.float32) a2_gs = torch.ones((e,), device="cuda", dtype=torch.float32) assert w1_gs is not None ...
1
test
vllm-project/vllm:tests/kernels/moe/test_nvfp4_moe.py:test_cutlass_fp4_moe_no_graph
ring_buffer = SingleWriterShmRingBuffer( data_buffer_size=self.buffer_size, create=True ) # Allocate some buffers for _ in range(3): self.ring_buffer.allocate_buf(100) # Clear the buffer self.ring_buffer.clear() # Check that metadata is empty an...
1
test
vllm-project/vllm:tests/distributed/test_shm_buffer.py:TestSingleWriterShmRingBuffer.test_clear_buffer
_ids (`list[int]`, *optional*): List of object IDs being tracked in the current frame. obj_id_to_mask (`dict[int, torch.FloatTensor]`, *optional*): Dictionary mapping object IDs to their predicted low-resolution masks. Each mask has shape `(1, H_low, W_low)`. obj_id_to_score (`dict[int, float]`, *optional*)...
0
documentation
huggingface/transformers:src/transformers/models/sam3_video/modeling_sam3_video.py:Sam3VideoSegmentationOutput:class_doc
[ [ [ [1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0], ] ]
1
test
keras-team/keras:keras/src/layers/pooling/adaptive_pooling2d_test.py:AdaptivePooling2DLayerTest.test_average_pooling2d_numerical
.is_output_node if cls._INPUT_IS_LIST is None: cls._INPUT_IS_LIST = schema.is_input_list if cls._NOT_IDEMPOTENT is None: cls._NOT_IDEMPOTENT = schema.not_idempotent if cls._ACCEPT_ALL_INPUTS is None: cls._ACCEPT_ALL_INPUTS = schema.accept_all_inputs i...
1
function_complex
Comfy-Org/ComfyUI:comfy_api/latest/_io.py:_ComfyNodeBaseInternal.GET_SCHEMA
f"{cuda_device_count_stateless()} exepected " f"{world_size}." ) config = Config( Ms=Ms, K=k, N=n, E=e, topks=TOPKs, dtype=dtype, quant_config=quant_config, prepare_finalize_type=prepare_finalize_type, fused_expert...
1
test
vllm-project/vllm:tests/kernels/moe/test_modular_kernel_combinations.py:test_modular_kernel_combinations_multigpu
a tensor of shape (batch_size, `rows`, `columns`, `num_channels` x `patch_height` x `patch_width`). Args: image_tensor (torch.Tensor): The image tensor to extract patches from. patch_height (int): The height of the patches to extract. patch_width (int): ...
0
function_simple
huggingface/transformers:src/transformers/models/kosmos2_5/image_processing_kosmos2_5_fast.py:torch_extract_patches
"""Test complete workflow: discover -> score -> filter -> use.""" # Step 1: Discover and score URLs config = SeedingConfig( source="sitemap", extract_head=True, query="premier league opening fixtures", scoring_method="bm25", score_threshold=0....
1
test
unclecode/crawl4ai:tests/general/test_async_url_seeder_bm25.py:TestAsyncUrlSeederBM25.test_full_workflow_integration
"addRecipeNutrition": True } try: search_response = requests.get(search_url, params=search_params, timeout=15) search_response.raise_for_status() search_data = search_response.json() if not search_data.get('results'): return {"error": f"No recipe ...
0
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/ai_recipe_meal_planning_agent/ai_recipe_meal_planning_agent.py:analyze_nutrition
index: int, ) -> None: """Process a single image response and send chunks.""" encoded_data = base64.b64encode(response.image_data).decode("utf-8") is_partial = isinstance(response, PartialImageResponse) # Extract stats from final ImageGenerationResponse if available stats = response.stats if isinsta...
0
function_simple
exo-explore/exo:src/exo/worker/runner/image_models/runner.py:_process_image_response
monkeypatch.setattr(module.REDIS_CONN, "get", lambda _key: (_ for _ in ()).throw(RuntimeError("trace boom"))) res = module.trace() assert res is None monkeypatch.setattr(module.UserCanvasService, "accessible", lambda *_args, **_kwargs: False) monkeypatch.setattr(module, "request", _DummyRequest(a...
1
test
infiniflow/ragflow:test/testcases/test_web_api/test_canvas_app/test_canvas_routes_unit.py:test_trace_and_sessions_matrix_unit
(), trigger=("messages", 5)) assert middleware._get_profile_limits() is None class MissingTokensModel(BaseChatModel): profile: ModelProfile | None = Field(default=ModelProfile(other_field=100), exclude=True) # type: ignore[typeddict-unknown-key] @override def _generate( se...
1
test
langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py:test_summarization_middleware_profile_edge_cases
value function tries to match the upper tail of the Q-value distribution. actor_lr: The learning rate for the actor network. Actor learning rates greater than critic learning rates work well in experiments. critic_lr: The learning rate for the Q-network. Critic l...
0
function_complex
ray-project/ray:rllib/algorithms/iql/iql.py:IQLConfig.training
requests.Session() pool_size = conf.getint(CONF_SECTION_NAME, CONF_REQUESTS_POOL_SIZE_KEY, fallback=10) retry_total = conf.getint(CONF_SECTION_NAME, CONF_REQUESTS_RETRIES_KEY, fallback=3) retry_strategy = Retry( total=retry_total, backoff_factor=0.1, status...
1
function_simple
apache/airflow:providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py:KeycloakAuthManager.http_session
.6], {"key": "value2"}), ] pgvector = PGVector( dbname="test_db", collection_name="test_collection", embedding_model_dims=3, user="test_user", password="test_pass", host="localhost", port=5432, diska...
1
test
mem0ai/mem0:tests/vector_stores/test_pgvector.py:TestPGVector.test_list_psycopg2
exists_s3_true(self): """Test file_exists returns True for existing S3 file.""" mock_settings = Mock() mock_settings.settings.storage_type = "s3" mock_storage = Mock() async def mock_get_size(_flow_id, _filename): return 100 mock_storage.get_file_size = moc...
1
test
langflow-ai/langflow:src/lfx/tests/unit/base/data/test_storage_utils.py:TestFileExists.test_file_exists_s3_true
mock_settings_service = MagicMock() mock_settings_service.settings.use_noop_database = True mock_get_settings.return_value = mock_settings_service # Create a mock graph with vertices graph = MagicMock(spec=Graph) vertex = MagicMock(spec=Vertex) vertex.id = "verte...
1
test
langflow-ai/langflow:src/lfx/tests/unit/cli/test_validation.py:TestValidateGlobalVariablesForEnv.test_non_string_values_ignored
excluded by active bounds if active_bounds and self._should_exclude_child(node, active_bounds): node.excluded_by_parent = True # Important: Still check if this node starts NEW propagation # Check if this node starts new propagation (even if excluded!) new_bounds = None tag = node.original_node.tag_name....
0
function_complex
browser-use/browser-use:browser_use/dom/serializer/serializer.py:DOMTreeSerializer._filter_tree_recursive
labels, boxes, scores]" ) labels_batch, boxes_batch, scores_batch = output_tensors[:3] batch_outputs: List[ObjectDetectionEngineOutput] = [] for idx, input_item in enumerate(input_batch): batch_outputs.append( self._build_output( inpu...
1
function_simple
docling-project/docling:docling/models/inference_engines/object_detection/onnxruntime_engine.py:OnnxRuntimeObjectDetectionEngine.predict_batch
# string to get the actual expression module_end_str = safe_eval(module_end_str, global_vars, local_vars) try: # Handle Polars DataFrame display options result = safe_eval(module_end_str, global_vars, local_vars) # Set display options for Polars if pr...
1
function_complex
run-llama/llama_index:llama-index-experimental/llama_index/experimental/query_engine/polars/output_parser.py:default_output_processor
task_id="test_table_to_file", source_table="source_db.source_table", target_file_name="/path/to/export.csv", teradata_conn_id="teradata_default", ) # Execute the operator result = operator.execute({}) # Verify the results assert result == 0...
1
test
apache/airflow:providers/teradata/tests/unit/teradata/operators/test_tpt.py:TestTdLoadOperator.test_table_to_file_mode
_extractions_overlap( extraction1: data.Extraction, extraction2: data.Extraction ) -> bool: """Checks if two extractions overlap based on their character intervals. Args: extraction1: First extraction to compare. extraction2: Second extraction to compare. Returns: True if the extractions overla...
1
function_simple
google/langextract:langextract/annotation.py:_extractions_overlap
_processor() video_processor = self.get_video_processor() processor = Ernie4_5_VLMoeProcessor( tokenizer=tokenizer, image_processor=image_processor, video_processor=video_processor ) processor.save_pretrained(self.tmpdirname) processor = Ernie4_5_VLMoeProcessor.from_...
0
test
huggingface/transformers:tests/models/ernie4_5_vl_moe/test_processing_ernie4_5_vl_moe.py:Ernie4_5_VLMoeProcessorTest.test_save_load_pretrained_default
]) loss = None if labels is not None: loss = self.loss_function( logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs ) return DeepseekVLHybridCausalLMOutputWithPast( loss=loss, logits=logits, ...
0
function_simple
huggingface/transformers:src/transformers/models/deepseek_vl_hybrid/modular_deepseek_vl_hybrid.py:DeepseekVLHybridForConditionalGeneration.forward
inputs_with_api_key = { "api_key": "sk-proj-MBZ6RyzaqpMgw_wwa123456789", "template": "Hello world", } transaction = TransactionBase( vertex_id="test-vertex", inputs=inputs_with_api_key, status="success", flow_id=flow_id, ...
1
test
langflow-ai/langflow:src/backend/tests/unit/api/v1/test_transactions.py:TestTransactionModels.test_transaction_base_sanitizes_sensitive_data_in_inputs
_and_inputs_for_common() # Let's make it always: # 1. use cache (for obvious reasons) # 2. generate to max length (which can be achieved by setting the eos token to an invalid value), which # would make the test flaky (e.g. EOS is generated on iteration 1 on both gene...
0
test
huggingface/transformers:tests/models/dia/test_modeling_dia.py:DiaModelTest.test_generate_continue_from_past_key_values
ync def on_BrowserConnectedEvent(self, event: BrowserConnectedEvent) -> None: """Grant permissions when browser connects.""" permissions = self.browser_session.browser_profile.permissions if not permissions: self.logger.debug('No permissions to grant') return self.logger.debug(f'🔓 Granting browser perm...
0
function_simple
browser-use/browser-use:browser_use/browser/watchdogs/permissions_watchdog.py:PermissionsWatchdog.on_BrowserConnectedEvent
if expert_indices.dtype != torch.int64: expert_indices = expert_indices.to(torch.int64) if len(expert_indices.shape) == 2: expert_indices = expert_indices.unsqueeze(2) expert_mask = torch.nn.functional.one_hot(expert_indices, num_experts) # For a given token, determine if it was routed...
0
function_simple
huggingface/transformers:src/transformers/models/switch_transformers/modular_switch_transformers.py:load_balancing_loss_func
""" 【工具】纯网页搜索: 只获取网页链接和摘要,不请求AI生成答案。 适用于需要快速获取原始网页信息,而不需要AI额外分析的场景。速度更快,成本更低。 """ logger.info(f"--- TOOL: 纯网页搜索 (query: {query}) ---") return self._search_internal(
1
function_simple
666ghj/BettaFish:MediaEngine/tools/search.py:BochaMultimodalSearch.web_search_only
first_pid = api._proc.pid # Verify we can't start another instance on the same port (SO_REUSEPORT disabled) config2 = HAProxyConfig( http_options=HTTPOptions( host="127.0.0.1", port=config.frontend_port, # Same port ), stats_port=8...
0
test
ray-project/ray:python/ray/serve/tests/test_haproxy_api.py:test_haproxy_start_should_throw_error_when_already_running
prefixed with `'lc_'` to indicate it is a LangChain-generated ID. """ if not any([url, base64, file_id]): msg = "Must provide one of: url, base64, or file_id" raise ValueError(msg) block = ImageContentBlock(type="image", id=ensure_id(id)) if url is not None: block["url"...
1
function_complex
langchain-ai/langchain:libs/core/langchain_core/messages/content.py:create_image_block
0.1:{haproxy_port}/slow"], kwargs={ "track_results": slow_results, "signal_started": request_started, }, ) slow_thread.start() wait_for_condition( lambda: request_started.is_set(), timeout=5, ret...
0
test
ray-project/ray:python/ray/serve/tests/test_haproxy_api.py:test_graceful_reload
self.logger.debug(f'[DownloadsWatchdog] Checking if browser auto-download saved the file for us: {suggested_filename}') # Poll for new files max_wait = 20 # seconds start_time = asyncio.get_event_loop().time() while asyncio.get_event_loop().time() - start_time < max_wait: # noqa: ASYNC110 await asynci...
0
function_complex
browser-use/browser-use:browser_use/browser/watchdogs/downloads_watchdog.py:DownloadsWatchdog._handle_cdp_download
ate_fn_map, pin_memory, ): """Tests that custom batch collate functions can be used to modify the batch before it is converted to a PyTorch tensor. Note that the collate_fn doesn't move the tensors to the device -- that happens in the iterator (finalize_fn). """ # Skip GPU tests if CUDA is ...
0
test
ray-project/ray:python/ray/train/tests/test_iter_torch_batches_gpu.py:test_custom_batch_collate_fn
{} podman_args = _podman_args( docker_image, extra_args=extra_podman_args, env=deployment_env ) if server_command: podman_args.append(server_command) # Build kwargs for the decorator: deploy_kwargs: Dict[str, Any] = { "name": name, "ray_actor_options": {"num_cpus": ...
0
function_simple
ray-project/ray:doc/source/ray-overview/examples/mcp-ray-serve/multi_mcp_ray_serve.py:build_mcp_deployment
_metric_type(node) if metric_type: name = self._extract_kwarg(node, "name") documentation = self._extract_kwarg(node, "documentation") if name: self.metrics.append( { "name": name, "type": me...
1
function_simple
vllm-project/vllm:docs/mkdocs/hooks/generate_metrics.py:MetricExtractor.visit_Call
# 收集所有 news_item_id 用于查询历史排名 news_ids = [row['id'] for row in rows] rank_history_map = {} if news_ids: placeholders = ",".join("?" * len(news_ids)) cursor.execute(f""" SELECT news_item_id, rank FROM rank_history WHERE news_item_id I...
1
function_complex
sansan0/TrendRadar:mcp_server/services/parser_service.py:ParserService._read_news_from_sqlite
["models_and_agents", "data", "openai"], ["openai", "models_and_agents", "data"], ["data", "openai", "models_and_agents"], ] for order in import_orders: try: for category_name in order: category_module = getattr(components, ca...
1
test
langflow-ai/langflow:src/backend/tests/unit/components/test_all_modules_importable.py:TestAllModulesImportable.test_no_circular_imports