dlib icon indicating copy to clipboard operation
dlib copied to clipboard

dlib’s find_min_global function creating SIGSEGV error

Open byronrogers73 opened this issue 3 years ago • 10 comments

We have created a custom training using the find_min_global function to search for the best parameters for an image landmarking program we have written.

We have run the python program in a pipeline on GCP with the following parameters

machine_type : n1-highcpu-64 max_func_calls: 100 params {"tree_depth": [2, 8, true], "nu": [0.001, 0.2, false], "cascade_depth": [6, 20, true], "feature_pool_size": [400, 1200, true], "num_test_splits": [20, 150, true], "oversampling_amount": [1, 50, true], "oversampling_translation_jitter": [0.0, 0.5, false], "feature_pool_region_padding": [-0.2, 0.2, false], "lambda_param": [0.01, 0.99, false]}

Expected Behavior

The code executes as it should, running through the iterations and training. It returns the saved predictor to file temp.dat and the training and testing error values...except it creates an error on one iteration (see below)

Current Behavior

We have run the code twice three times, and it gets through the iterations until it reaches the following parameters

shape_predictor_training_options(be_verbose=1, cascade_depth=7, tree_depth=3, num_trees_per_cascade_level=500, nu=0.0352574, oversampling_amount=1, oversampling_translation_jitter=0.492069, feature_pool_size=1168, lambda_param=0.909473, num_test_splits=143, feature_pool_region_padding=0.0857562, random_seed=, num_threads=64, landmark_relative_padding_mode=1)

This produces : Fatal Python error: Segmentation fault. The replica workerpool0-0 exited with a non-zero status of 139(SIGSEGV)

Every time we have run the code it has produced the correct output (getting through 20 or so iterations) and then it fails on this one parameter setting.

Steps to Reproduce

I have outlined the steps that we took to get to the issue above.

  • Version: v19.24
  • Where did you get dlib: this Github
  • Platform: Google Clould Platform. Vertex AI pipeline n1-highcpu-64.
  • Compiler: python 3.9

byronrogers73 avatar Mar 09 '23 23:03 byronrogers73

Please post a minimal program that reproduces the error when run.

davisking avatar Mar 10 '23 00:03 davisking

Requirements.txt

dlib==19.24.0 google-cloud-bigquery==2.34.4 google-cloud-storage==1.44.0 google-cloud-secret-manager==2.12.6 google-cloud-firestore==2.10.0 db-dtypes==1.0.4 gcsfs==2022.5.0 opencv-python==4.5.5.64 numpy==1.23.4 flask==2.2.2 mailjet_rest==1.3.4 gunicorn==20.1.0

byronrogers73 avatar Mar 10 '23 18:03 byronrogers73

Morph_Parameters_Tuning_Pipeline

import json

import google.cloud.aiplatform as aip
from google_cloud_pipeline_components import aiplatform as gcc_aip
from kfp.v2 import dsl
from kfp.v2 import compiler
from kfp.v2.dsl import component
from kfp.v2.dsl import (
    Input,
    Artifact,
)


@component(
    base_image='python:3.9',
    packages_to_install=['google-cloud-bigquery', 'pandas', 'pyarrow', 'db-dtypes', 'google-cloud-storage', 'fsspec',
                         'gcsfs']
)
def get_dataset_data(gcp_project: str, pipeline_root: str) -> str:
    import json
    import datetime

    import pandas as pd
    from google.cloud import bigquery

    def format_landmarks(calculated_data):
        landmarks = calculated_data['edited_landmarks']
        landmarks = sorted(landmarks, key=lambda x: x['id'])
        landmarks_lst = []
        for landmark in landmarks:
            land_x = landmark['x']
            land_y = landmark['y']
            landmarks_lst.append(str(land_x))
            landmarks_lst.append(str(land_y))
        landmarks_fmt = ",".join(landmarks_lst)
        landmarks_no = len(landmarks_lst)
        if landmarks_no != 40:
            print(landmarks_no)
        return pd.Series(landmarks_lst)

    bq = bigquery.Client(project=gcp_project)
    df = bq.query(
        "SELECT image, calculated_data FROM `velox-horse1.velox_webapp_db.image_measurement` WHERE calculated_data IS NOT NULL").to_dataframe()
    df['image'] = df['image'].apply(lambda image: json.loads(image))
    df['calculated_data'] = df['calculated_data'].apply(lambda data: json.loads(data))
    df['landmarks'] = df['calculated_data'].apply(lambda x: x['edited_landmarks'])
    df['image_filename'] = df['image'].apply(lambda image: image['filename'])
    df['image_gcs_path'] = df['image'].apply(lambda image: f'{image["path"]}')
    df['image_gcs_uri'] = df['image'].apply(lambda image: f'gs://{image["bucket"]}/{image["path"]}')

    dfx = df['calculated_data'].apply(format_landmarks)
    res_df = pd.concat([df, dfx], axis=1, join='inner')
    columns = ['image_gcs_uri'] + list(range(0, 40))
    ts = datetime.datetime.utcnow().strftime('%Y%m%d_%H%M%S')
    gcs_path = f'{pipeline_root}/dataset_input/{ts}.csv'
    dataset_input_file_path = f'gs://{gcs_path}'
    res_df[columns].to_csv(dataset_input_file_path, index=False)
    return dataset_input_file_path


@component(
    base_image='python:3.9',
    packages_to_install=['google-cloud-aiplatform']
)
def run_custom_job(display_name: str, container_uri: str, staging_bucket: str, params: str, max_func_calls: int,
                   dataset: Input[Artifact]
                   ):
    from google.cloud.aiplatform import CustomContainerTrainingJob, TabularDataset

    dataset_id = dataset.metadata['resourceName']
    ds = TabularDataset(dataset_id)

    custom_job = CustomContainerTrainingJob(
        display_name=display_name,
        container_uri=container_uri,
        staging_bucket=staging_bucket,
        command=['python', 'vertex_parameter_tuning.py']
    )

    custom_job.run(
        dataset=ds,
        service_account='[email protected]',
        training_fraction_split=1.0,
        replica_count=1,
        machine_type='n1-highcpu-64',
        args=[f"--params={params}"],
        environment_variables={'MAX_FUNC_CALLS': str(max_func_calls)}
    )


@dsl.pipeline()
def pipeline(
        gcp_project: str,
        pipeline_root: str,
        pipeline_name: str,
        container_uri: str,
        custom_training_bucket: str,
        max_func_calls: int,
        params: str,
):
    dataset_file_op = get_dataset_data(gcp_project, pipeline_root)

    tabular_dataset_create_op = gcc_aip.TabularDatasetCreateOp(
        project=gcp_project,
        display_name=pipeline_name,
        gcs_source=dataset_file_op.output,
    )

    run_custom_job(display_name, container_uri, custom_training_bucket, params, max_func_calls,
                   tabular_dataset_create_op.outputs['dataset'])


def compile_upload(pipeline_export_filepath: str):
    from google.cloud import storage
    compiler.Compiler().compile(pipeline_func=pipeline,
                                pipeline_name=display_name,
                                package_path=pipeline_export_filepath)
    gcs_bucket = 'velox-vertex-ai'
    gcs_path = 'compiled_pipelines'
    blob_path = f'{gcs_path}/{pipeline_export_filepath}'
    gcs = storage.Client(project=gcp_project)
    bucket = gcs.bucket(gcs_bucket)
    blob = bucket.blob(blob_path)
    blob.upload_from_filename(pipeline_export_filepath)


def run(pipeline_export_filepath: str, display_name: str, gcp_project: str, custom_training_bucket: str,
        pipeline_bucket: str, max_func_calls: int, params: dict):
    pipeline_root = f"{pipeline_bucket}/pipeline_root/{display_name}"

    compiler.Compiler().compile(pipeline_func=pipeline,
                                pipeline_name=display_name,
                                package_path=pipeline_export_filepath)

    params_json = json.dumps(params)

    pipeline_params = {
        'gcp_project': gcp_project,
        'pipeline_root': pipeline_root,
        'pipeline_name': display_name,
        'container_uri': 'gcr.io/velox-horse1/morph-landmarks',
        'custom_training_bucket': custom_training_bucket,
        'max_func_calls': max_func_calls,
        'params': params_json
    }

    job = aip.PipelineJob(
        display_name=display_name,
        template_path=pipeline_export_filepath,
        pipeline_root=f'gs://{pipeline_root}',
        project=gcp_project,
        parameter_values=pipeline_params,
        enable_caching=False
    )

    job.submit()


if __name__ == '__main__':
    display_name = 'morph-landmarks-parameters-tuning'
    custom_training_bucket = 'velox-vertex-ai-custom-training'
    pipeline_bucket = 'velox-vertex-ai'
    gcp_project = 'velox-horse1'
    pipeline_export_filepath = f'{display_name}.json'

    params = dict([
        ("tree_depth", (2, 8, True)),
        ("nu", (0.001, 0.2, False)),
        ("cascade_depth", (6, 20, True)),
        ("feature_pool_size", (400, 1200, True)),
        ("num_test_splits", (20, 150, True)),
        ("oversampling_amount", (1, 50, True)),
        ("oversampling_translation_jitter", (0.0, 0.5, False)),
        ("feature_pool_region_padding", (-0.2, 0.2, False)),
        ("lambda_param", (0.01, 0.99, False))
    ])
    max_func_calls = 100
    # compile_upload(pipeline_export_filepath)
    run(pipeline_export_filepath, display_name, gcp_project, custom_training_bucket, pipeline_bucket, max_func_calls,
        params)

byronrogers73 avatar Mar 10 '23 18:03 byronrogers73

Ha ok, I mean, can you give something that I can run on my laptop that reproduces the problem? :)

davisking avatar Mar 10 '23 22:03 davisking

I have sent you the code, etc. I should have also mentioned that the script is running inside a Docker container on the 64 CPUs machine

byronrogers73 avatar Mar 12 '23 14:03 byronrogers73

I'm running this now. Looks like it's going to run for many hours before it gets to the problem. Is there a fast way to make it happen?

davisking avatar Mar 12 '23 19:03 davisking

As an aside, the training and test data looks really wrong. Like image

The keypoints don't appear to be on anything. It looks like some program was run that transformed the points somehow and messed them all up.

davisking avatar Mar 12 '23 19:03 davisking

Hi

It looks like the image measurements are inverted the Y axis in the XML parse and by correcting that, the process worked

byronrogers73 avatar Mar 12 '23 19:03 byronrogers73

So far this hasn't reproduced for me. I let it run for about 10 hours and it appeared to be working. Does running the script you sent me error out for you?

davisking avatar Mar 14 '23 12:03 davisking

We did actually manage to get it to produce the optimal parameters and have the model train with those parameters

Screenshot 2023-03-31 at 10 24 00 AM

byronrogers73 avatar Mar 31 '23 14:03 byronrogers73