Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow setting min_time in Python API #635

Merged
merged 3 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
# Dev

## Breaking change
* The output format of the `job info` command with JSON output mode has been changed. Note that
the JSON output mode is still unstable.

## New features
* Allow setting minimum duration for a task (`min_time` resource value) using the Python API.

# v0.17.0

## Breaking change
Expand Down
203 changes: 118 additions & 85 deletions crates/hyperqueue/src/client/output/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,90 +80,63 @@ impl Output for JsonOutput {
self.print(json!(statuses))
}
fn print_job_detail(&self, jobs: Vec<JobDetail>, _worker_map: WorkerMap, server_uid: &str) {
let job_details: Vec<_> = jobs.into_iter().map(|job| {
let task_paths = resolve_task_paths(&job, server_uid);

let JobDetail {
info,
job_desc,
tasks,
tasks_not_found: _,
max_fails,
submission_date,
completion_date_or_now,
submit_dir,
} = job;

let finished_at = if info.counters.is_terminated(info.n_tasks) {
Some(completion_date_or_now)
} else {
None
};

let mut json = json!({
"info": format_job_info(info),
"max_fails": max_fails,
"started_at": format_datetime(submission_date),
"finished_at": finished_at.map(format_datetime),
"submit_dir": submit_dir
});

if let JobDescription::Array {
task_desc:
TaskDescription {
program:
ProgramDefinition {
args,
env,
stdout,
stderr,
cwd,
stdin: _,
},
resources,
pin_mode,
time_limit,
priority,
task_dir,
crash_limit,
},
..
} = job_desc
{
json["program"] = json!({
"args": args.into_iter().map(|args| args.to_string()).collect::<Vec<_>>(),
"env": env.into_iter().map(|(key, value)| (key.to_string(), value.to_string())).collect::<Map<String, String>>(),
"cwd": cwd,
"stderr": format_stdio_def(&stderr),
"stdout": format_stdio_def(&stdout),
});
json["resources"] = resources.variants.into_iter().map(|v| {
let ResourceRequest { n_nodes, resources, min_time } = v;
json!({
"n_nodes": n_nodes,
"resources": resources.into_iter().map(|res| {
json!({
"resource": res.resource,
"request": res.policy
})
}).collect::<Vec<_>>(),
"min_time": format_duration(min_time)
})}
).collect();
json["pin_mode"] = json!(match pin_mode {
PinMode::None => None,
PinMode::OpenMP => Some("openmp"),
PinMode::TaskSet => Some("taskset"),
let job_details: Vec<_> = jobs
.into_iter()
.map(|job| {
let task_paths = resolve_task_paths(&job, server_uid);

let JobDetail {
info,
job_desc,
tasks,
tasks_not_found: _,
max_fails,
submission_date,
completion_date_or_now,
submit_dir,
} = job;

let finished_at = if info.counters.is_terminated(info.n_tasks) {
Some(completion_date_or_now)
} else {
None
};

let mut json = json!({
"info": format_job_info(info),
"max_fails": max_fails,
"started_at": format_datetime(submission_date),
"finished_at": finished_at.map(format_datetime),
"submit_dir": submit_dir
});
json["priority"] = json!(priority);
json["time_limit"] = json!(time_limit.map(format_duration));
json["task_dir"] = json!(task_dir);
json["crash_limit"] = json!(crash_limit);
}

json["tasks"] = format_tasks(tasks, task_paths);
json
}).collect();
let task_description = match job_desc {
JobDescription::Array { task_desc, .. } => {
let mut task = json!({});
format_task_description(task_desc, &mut task);
json!({
"array": task
})
}
JobDescription::Graph { tasks } => {
let tasks: Vec<Value> = tasks
.into_iter()
.map(|task| {
let mut json = json!({});
format_task_description(task.task_desc, &mut json);
json
})
.collect();
json!({
"graph": tasks
})
}
};
json["task-desc"] = task_description;
json["tasks"] = format_tasks(tasks, task_paths);
json
})
.collect();
self.print(Value::Array(job_details));
}

Expand Down Expand Up @@ -216,12 +189,14 @@ impl Output for JsonOutput {

fn print_task_info(
&self,
_job: (JobId, JobDetail),
_tasks: Vec<JobTaskInfo>,
job: (JobId, JobDetail),
tasks: Vec<JobTaskInfo>,
_worker_map: WorkerMap,
_server_uid: &str,
server_uid: &str,
_verbosity: Verbosity,
) {
let map = resolve_task_paths(&job.1, server_uid);
self.print(format_tasks(tasks, map));
}

fn print_summary(&self, filename: &Path, summary: Summary) {
Expand Down Expand Up @@ -257,6 +232,64 @@ impl Output for JsonOutput {
}
}

fn format_task_description(task_desc: TaskDescription, json: &mut Value) {
let TaskDescription {
program:
ProgramDefinition {
args,
env,
stdout,
stderr,
cwd,
stdin: _,
},
resources,
pin_mode,
time_limit,
priority,
task_dir,
crash_limit,
} = task_desc;

json["program"] = json!({
"args": args.into_iter().map(|args| args.to_string()).collect::<Vec<_>>(),
"env": env.into_iter().map(|(key, value)| (key.to_string(), value.to_string())).collect::<Map<String, String>>(),
"cwd": cwd,
"stderr": format_stdio_def(&stderr),
"stdout": format_stdio_def(&stdout),
});
json["resources"] = resources
.variants
.into_iter()
.map(|v| {
let ResourceRequest {
n_nodes,
resources,
min_time,
} = v;
json!({
"n_nodes": n_nodes,
"resources": resources.into_iter().map(|res| {
json!({
"resource": res.resource,
"request": res.policy
})
}).collect::<Vec<_>>(),
"min_time": format_duration(min_time)
})
})
.collect();
json["pin_mode"] = json!(match pin_mode {
PinMode::None => None,
PinMode::OpenMP => Some("openmp"),
PinMode::TaskSet => Some("taskset"),
});
json["priority"] = json!(priority);
json["time_limit"] = json!(time_limit.map(format_duration));
json["task_dir"] = json!(task_dir);
json["crash_limit"] = json!(crash_limit);
}

fn fill_task_started_data(dict: &mut Value, data: StartedTaskData) {
dict["started_at"] = format_datetime(data.start_date);
if data.worker_ids.len() == 1 {
Expand Down
6 changes: 5 additions & 1 deletion crates/pyhq/python/hyperqueue/ffi/protocol.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import dataclasses
import datetime
from typing import Dict, List, Optional, Sequence, Union

from ..output import StdioDef
Expand All @@ -7,22 +8,25 @@
class ResourceRequest:
n_nodes: int = 0
resources: Dict[str, Union[int, float, str]] = dataclasses.field(default_factory=dict)
min_time: Optional[float] = None

def __init__(
self,
*,
n_nodes=0,
cpus: Union[int, float, str] = 1,
resources: Optional[Dict[str, Union[int, float, str]]] = None,
min_time: Optional[datetime.timedelta] = None,
):
self.n_nodes = n_nodes
if resources is None:
resources = {}
resources["cpus"] = cpus
self.resources = resources
self.min_time = min_time.total_seconds() if min_time is not None else None

def __repr__(self):
return f"<ResourceRequest n_nodes={self.n_nodes} resources={self.resources}>"
return f"<ResourceRequest n_nodes={self.n_nodes} resources={self.resources} min_time={self.min_time}>"


@dataclasses.dataclass()
Expand Down
5 changes: 3 additions & 2 deletions crates/pyhq/src/client/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use tako::gateway::{ResourceRequestEntries, ResourceRequestEntry, ResourceReques
use tako::program::{FileOnCloseBehavior, ProgramDefinition, StdioDef};
use tako::resources::{AllocationRequest, NumOfNodes, ResourceAmount};

use crate::marshal::FromPy;
use crate::marshal::{FromPy, WrappedDuration};
use crate::utils::error::ToPyResult;
use crate::{borrow_mut, run_future, ClientContextPtr, FromPyObject, PyJobId, PyTaskId};

Expand All @@ -38,6 +38,7 @@ enum AllocationValue {
pub struct ResourceRequestDescription {
n_nodes: NumOfNodes,
resources: HashMap<String, AllocationValue>,
min_time: Option<WrappedDuration>,
}

#[derive(Debug, FromPyObject)]
Expand Down Expand Up @@ -182,7 +183,7 @@ fn build_task_desc(desc: TaskDescription, submit_dir: &Path) -> anyhow::Result<H
})
})
.collect::<anyhow::Result<ResourceRequestEntries>>()?,
min_time: Default::default(),
min_time: rq.min_time.map(|v| v.into()).unwrap_or_default(),
})
})
.collect::<anyhow::Result<_>>()?,
Expand Down
6 changes: 6 additions & 0 deletions crates/pyhq/src/marshal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,9 @@ impl<'a> FromPyObject<'a> for WrappedDuration {
Ok(WrappedDuration(Duration::from_nanos(nanoseconds as u64)))
}
}

impl From<WrappedDuration> for Duration {
fn from(value: WrappedDuration) -> Self {
value.0
}
}
Loading
Loading