Exemple #1
0
def get_loss_profile(project_id: str, profile_id: str):
    """
    Route for getting a specific loss profile for a given project.
    Raises an HTTPNotFoundError if the project or loss profile are
    not found in the database.

    :param project_id: the id of the project to get the loss profile for
    :param profile_id: the id of the loss profile to get
    :return: a tuple containing (json response, http status code)
    """
    _LOGGER.info("getting loss profile for project {} with id {}".format(
        project_id, profile_id))

    get_project_by_id(project_id)  # validate id

    # search for loss profile and verify that project_id matches
    loss_profile = ProjectLossProfile.get_or_none(
        ProjectLossProfile.profile_id == profile_id,
        ProjectLossProfile.project_id == project_id,
    )
    if loss_profile is None:
        _LOGGER.error(
            "could not find loss profile with profile_id {} and project_id {}".
            format(profile_id, project_id))
        raise HTTPNotFoundError(
            "could not find loss profile with profile_id {} and project_id {}".
            format(profile_id, project_id))

    resp_profile = data_dump_and_validation(ResponseProjectLossProfileSchema(),
                                            {"profile": loss_profile})
    _LOGGER.info(
        "found loss profile with profile_id {} and project_id: {}".format(
            profile_id, project_id))

    return jsonify(resp_profile), HTTPStatus.OK.value
Exemple #2
0
def get_loss_profiles(project_id: str):
    """
    Route for getting a list of project loss profiles filtered by the flask request args
    Raises an HTTPNotFoundError if the project is not found in the database.

    :param project_id: the id of the project to get the loss profiles for
    :return: a tuple containing (json response, http status code)
    """
    args = {key: val for key, val in request.args.items()}
    _LOGGER.info(
        "getting project optims for project_id {} and request args {}".format(
            project_id, args))
    args = SearchProjectProfilesSchema().load(args)
    get_project_by_id(project_id)  # validate id

    loss_profiles_query = (ProjectLossProfile.select().where(
        ProjectLossProfile.project_id == project_id).order_by(
            ProjectLossProfile.created).paginate(args["page"],
                                                 args["page_length"]))
    loss_profiles = [res for res in loss_profiles_query]

    resp_profiles = data_dump_and_validation(
        ResponseProjectLossProfilesSchema(), {"profiles": loss_profiles})
    _LOGGER.info("retrieved {} profiles".format(len(loss_profiles)))

    return jsonify(resp_profiles), HTTPStatus.OK.value
Exemple #3
0
def upload_loss_profile(project_id: str):
    """
    Route for creating a new loss profile for a given project from uploaded data.
    Raises an HTTPNotFoundError if the project is not found in the database.

    :param project_id: the id of the project to create a loss profile for
    :return: a tuple containing (json response, http status code)
    """
    _LOGGER.info("uploading loss profile for project {}".format(project_id))

    project = get_project_by_id(project_id)  # validate id

    if "loss_file" not in request.files:
        _LOGGER.error("missing uploaded file 'loss_file'")
        raise ValidationError("missing uploaded file 'loss_file'")

    # read loss analysis file
    try:
        loss_analysis = json.load(request.files["loss_file"])  # type: Dict
    except Exception as err:
        _LOGGER.error(
            "error while reading uploaded loss analysis file: {}".format(err))
        raise ValidationError(
            "error while reading uploaded loss analysis file: {}".format(err))

    # override or default potential previous data fields
    loss_analysis_args = CreateProjectLossProfileSchema().load(loss_analysis)
    loss_analysis.update(loss_analysis_args)
    loss_analysis["profile_id"] = "<none>"
    loss_analysis["project_id"] = "<none>"
    loss_analysis["created"] = datetime.datetime.now()
    loss_analysis["source"] = "uploaded"
    loss_analysis["job"] = None

    loss_analysis = data_dump_and_validation(ProjectLossProfileSchema(),
                                             loss_analysis)
    del loss_analysis["profile_id"]  # delete to create a new one on DB insert
    del loss_analysis[
        "project_id"]  # delete because project is passed in on DB insert

    model = project.model
    if model is None:
        raise ValidationError(
            ("A model has not been set for the project with id {}, "
             "project must set a model before running a loss profile."
             ).format(project_id))

    loss_profile = ProjectLossProfile.create(project=project, **loss_analysis)

    resp_profile = data_dump_and_validation(ResponseProjectLossProfileSchema(),
                                            {"profile": loss_profile})
    _LOGGER.info("created loss profile: id: {}, name: {}".format(
        resp_profile["profile"]["profile_id"],
        resp_profile["profile"]["name"]))

    return jsonify(resp_profile), HTTPStatus.OK.value
Exemple #4
0
    def _get_project_loss_profile(self) -> ProjectLossProfile:
        loss_profile = ProjectLossProfile.get_or_none(
            ProjectLossProfile.profile_id == self._profile_id)

        if loss_profile is None:
            raise ValueError(
                "ProjectLossProfile with profile_id {} was not found".format(
                    self._profile_id))

        return loss_profile
def get_profiles_by_id(
    profile_perf_id: Union[None, str], profile_loss_id: Union[None, str]
) -> Tuple[ProjectPerfProfile, ProjectLossProfile]:
    """
    Get a performance and loss profile by their ids.
    If not found will return None instead of raising not found.

    :param profile_perf_id: id of the performance profile to get
    :param profile_loss_id: id of the loss profile to get
    :return: tuple containing (performance profile, loss profile)
    """
    profile_perf = (ProjectPerfProfile.get_or_none(
        ProjectPerfProfile.profile_id == profile_perf_id)
                    if profile_perf_id else None)
    profile_loss = (ProjectLossProfile.get_or_none(
        ProjectLossProfile.profile_id == profile_loss_id)
                    if profile_loss_id else None)

    return profile_perf, profile_loss
Exemple #6
0
def create_loss_profile(project_id: str):
    """
    Route for creating a new loss profile for a given project.
    Raises an HTTPNotFoundError if the project is not found in the database.

    :param project_id: the id of the project to create a loss profile for
    :return: a tuple containing (json response, http status code)
    """
    _LOGGER.info(
        "creating loss profile for project {} for request json {}".format(
            project_id, request.json))
    project = get_project_by_id(project_id)

    loss_profile_params = CreateProjectLossProfileSchema().load(
        request.get_json(force=True))

    model = project.model
    if model is None:
        raise ValidationError(
            ("A model has not been set for the project with id {}, "
             "project must set a model before running a loss profile."
             ).format(project_id))
    loss_profile = None
    job = None

    try:
        loss_profile = ProjectLossProfile.create(project=project,
                                                 source="generated",
                                                 **loss_profile_params)
        job = Job.create(
            project_id=project_id,
            type_=CreateLossProfileJobWorker.get_type(),
            worker_args=CreateLossProfileJobWorker.format_args(
                model_id=model.model_id,
                profile_id=loss_profile.profile_id,
                pruning_estimations=loss_profile_params["pruning_estimations"],
                pruning_estimation_type=loss_profile_params[
                    "pruning_estimation_type"],
                pruning_structure=loss_profile_params["pruning_structure"],
                quantized_estimations=loss_profile_params[
                    "quantized_estimations"],
            ),
        )
        loss_profile.job = job
        loss_profile.save()
    except Exception as err:
        _LOGGER.error(
            "error while creating new loss profile, rolling back: {}".format(
                err))
        if loss_profile:
            try:
                loss_profile.delete_instance()
            except Exception as rollback_err:
                _LOGGER.error(
                    "error while rolling back new loss profile: {}".format(
                        rollback_err))
        if job:
            try:
                job.delete_instance()
            except Exception as rollback_err:
                _LOGGER.error(
                    "error while rolling back new loss profile: {}".format(
                        rollback_err))
        raise err

    # call into JobWorkerManager to kick off job if it's not already running
    JobWorkerManager().refresh()

    resp_profile = data_dump_and_validation(ResponseProjectLossProfileSchema(),
                                            {"profile": loss_profile})
    _LOGGER.info("created loss profile and job: {}".format(resp_profile))

    return jsonify(resp_profile), HTTPStatus.OK.value