Add files using upload-large-folder tool
Browse files- grounding-dino/.eval_venv/bin/Activate.ps1 +247 -0
- grounding-dino/.eval_venv/bin/activate +63 -0
- grounding-dino/.eval_venv/bin/activate.csh +26 -0
- grounding-dino/.eval_venv/bin/activate.fish +69 -0
- grounding-dino/.eval_venv/bin/cygdb +6 -0
- grounding-dino/.eval_venv/bin/cython +6 -0
- grounding-dino/.eval_venv/bin/cythonize +6 -0
- grounding-dino/.eval_venv/bin/f2py +6 -0
- grounding-dino/.eval_venv/bin/pip +8 -0
- grounding-dino/.eval_venv/bin/pip3 +8 -0
- grounding-dino/.eval_venv/bin/pip3.11 +8 -0
- grounding-dino/.eval_venv/bin/wgit +6 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/__editable___mmdet_3_3_0_finder.py +85 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/__init__.py +4 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/__pycache__/fsdp.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/__pycache__/moe.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/__pycache__/oss.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/__pycache__/utils.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/__init__.py +4 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/__pycache__/__init__.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/__pycache__/mnist.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/__pycache__/wikitext2_data.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/mnist.py +38 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/wikitext2_data.py +107 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/fsdp.py +404 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/__init__.py +4 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/__pycache__/__init__.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/__pycache__/lm_wikitext2.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/__pycache__/oss_mnist.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/lm_wikitext2.py +163 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/oss_mnist.py +18 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/models/__init__.py +4 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/models/__pycache__/__init__.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/models/__pycache__/transformer_lm.cpython-311.pyc +0 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/moe.py +130 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/oss.py +350 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/pipe.py +314 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/utils.py +167 -0
- grounding-dino/.eval_venv/lib/python3.11/site-packages/cython.py +29 -0
- grounding-dino/.eval_venv/pyvenv.cfg +5 -0
- grounding-dino/compute_recall_f1.py +229 -0
- grounding-dino/convert_pkl_to_answer_jsonl.py +296 -0
- grounding-dino/data_precess_train.py +167 -0
- grounding-dino/data_precess_val.py +141 -0
- grounding-dino/evaluate_with_rex_omni.py +288 -0
- grounding-dino/inference_crop_grounding_dino.py +506 -0
- grounding-dino/run_eval_and_vis.sh +203 -0
- grounding-dino/run_eval_rex_style.sh +193 -0
- grounding-dino/run_train.sh +86 -0
- grounding-dino/train_mm_grounding_dino.sh +177 -0
grounding-dino/.eval_venv/bin/Activate.ps1
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<#
|
| 2 |
+
.Synopsis
|
| 3 |
+
Activate a Python virtual environment for the current PowerShell session.
|
| 4 |
+
|
| 5 |
+
.Description
|
| 6 |
+
Pushes the python executable for a virtual environment to the front of the
|
| 7 |
+
$Env:PATH environment variable and sets the prompt to signify that you are
|
| 8 |
+
in a Python virtual environment. Makes use of the command line switches as
|
| 9 |
+
well as the `pyvenv.cfg` file values present in the virtual environment.
|
| 10 |
+
|
| 11 |
+
.Parameter VenvDir
|
| 12 |
+
Path to the directory that contains the virtual environment to activate. The
|
| 13 |
+
default value for this is the parent of the directory that the Activate.ps1
|
| 14 |
+
script is located within.
|
| 15 |
+
|
| 16 |
+
.Parameter Prompt
|
| 17 |
+
The prompt prefix to display when this virtual environment is activated. By
|
| 18 |
+
default, this prompt is the name of the virtual environment folder (VenvDir)
|
| 19 |
+
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
|
| 20 |
+
|
| 21 |
+
.Example
|
| 22 |
+
Activate.ps1
|
| 23 |
+
Activates the Python virtual environment that contains the Activate.ps1 script.
|
| 24 |
+
|
| 25 |
+
.Example
|
| 26 |
+
Activate.ps1 -Verbose
|
| 27 |
+
Activates the Python virtual environment that contains the Activate.ps1 script,
|
| 28 |
+
and shows extra information about the activation as it executes.
|
| 29 |
+
|
| 30 |
+
.Example
|
| 31 |
+
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
|
| 32 |
+
Activates the Python virtual environment located in the specified location.
|
| 33 |
+
|
| 34 |
+
.Example
|
| 35 |
+
Activate.ps1 -Prompt "MyPython"
|
| 36 |
+
Activates the Python virtual environment that contains the Activate.ps1 script,
|
| 37 |
+
and prefixes the current prompt with the specified string (surrounded in
|
| 38 |
+
parentheses) while the virtual environment is active.
|
| 39 |
+
|
| 40 |
+
.Notes
|
| 41 |
+
On Windows, it may be required to enable this Activate.ps1 script by setting the
|
| 42 |
+
execution policy for the user. You can do this by issuing the following PowerShell
|
| 43 |
+
command:
|
| 44 |
+
|
| 45 |
+
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
|
| 46 |
+
|
| 47 |
+
For more information on Execution Policies:
|
| 48 |
+
https://go.microsoft.com/fwlink/?LinkID=135170
|
| 49 |
+
|
| 50 |
+
#>
|
| 51 |
+
Param(
|
| 52 |
+
[Parameter(Mandatory = $false)]
|
| 53 |
+
[String]
|
| 54 |
+
$VenvDir,
|
| 55 |
+
[Parameter(Mandatory = $false)]
|
| 56 |
+
[String]
|
| 57 |
+
$Prompt
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
<# Function declarations --------------------------------------------------- #>
|
| 61 |
+
|
| 62 |
+
<#
|
| 63 |
+
.Synopsis
|
| 64 |
+
Remove all shell session elements added by the Activate script, including the
|
| 65 |
+
addition of the virtual environment's Python executable from the beginning of
|
| 66 |
+
the PATH variable.
|
| 67 |
+
|
| 68 |
+
.Parameter NonDestructive
|
| 69 |
+
If present, do not remove this function from the global namespace for the
|
| 70 |
+
session.
|
| 71 |
+
|
| 72 |
+
#>
|
| 73 |
+
function global:deactivate ([switch]$NonDestructive) {
|
| 74 |
+
# Revert to original values
|
| 75 |
+
|
| 76 |
+
# The prior prompt:
|
| 77 |
+
if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
|
| 78 |
+
Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
|
| 79 |
+
Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
# The prior PYTHONHOME:
|
| 83 |
+
if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
|
| 84 |
+
Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
|
| 85 |
+
Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
# The prior PATH:
|
| 89 |
+
if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
|
| 90 |
+
Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
|
| 91 |
+
Remove-Item -Path Env:_OLD_VIRTUAL_PATH
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
# Just remove the VIRTUAL_ENV altogether:
|
| 95 |
+
if (Test-Path -Path Env:VIRTUAL_ENV) {
|
| 96 |
+
Remove-Item -Path env:VIRTUAL_ENV
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
# Just remove VIRTUAL_ENV_PROMPT altogether.
|
| 100 |
+
if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
|
| 101 |
+
Remove-Item -Path env:VIRTUAL_ENV_PROMPT
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
# Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
|
| 105 |
+
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
|
| 106 |
+
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
# Leave deactivate function in the global namespace if requested:
|
| 110 |
+
if (-not $NonDestructive) {
|
| 111 |
+
Remove-Item -Path function:deactivate
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
<#
|
| 116 |
+
.Description
|
| 117 |
+
Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
|
| 118 |
+
given folder, and returns them in a map.
|
| 119 |
+
|
| 120 |
+
For each line in the pyvenv.cfg file, if that line can be parsed into exactly
|
| 121 |
+
two strings separated by `=` (with any amount of whitespace surrounding the =)
|
| 122 |
+
then it is considered a `key = value` line. The left hand string is the key,
|
| 123 |
+
the right hand is the value.
|
| 124 |
+
|
| 125 |
+
If the value starts with a `'` or a `"` then the first and last character is
|
| 126 |
+
stripped from the value before being captured.
|
| 127 |
+
|
| 128 |
+
.Parameter ConfigDir
|
| 129 |
+
Path to the directory that contains the `pyvenv.cfg` file.
|
| 130 |
+
#>
|
| 131 |
+
function Get-PyVenvConfig(
|
| 132 |
+
[String]
|
| 133 |
+
$ConfigDir
|
| 134 |
+
) {
|
| 135 |
+
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
|
| 136 |
+
|
| 137 |
+
# Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
|
| 138 |
+
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
|
| 139 |
+
|
| 140 |
+
# An empty map will be returned if no config file is found.
|
| 141 |
+
$pyvenvConfig = @{ }
|
| 142 |
+
|
| 143 |
+
if ($pyvenvConfigPath) {
|
| 144 |
+
|
| 145 |
+
Write-Verbose "File exists, parse `key = value` lines"
|
| 146 |
+
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
|
| 147 |
+
|
| 148 |
+
$pyvenvConfigContent | ForEach-Object {
|
| 149 |
+
$keyval = $PSItem -split "\s*=\s*", 2
|
| 150 |
+
if ($keyval[0] -and $keyval[1]) {
|
| 151 |
+
$val = $keyval[1]
|
| 152 |
+
|
| 153 |
+
# Remove extraneous quotations around a string value.
|
| 154 |
+
if ("'""".Contains($val.Substring(0, 1))) {
|
| 155 |
+
$val = $val.Substring(1, $val.Length - 2)
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
$pyvenvConfig[$keyval[0]] = $val
|
| 159 |
+
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
}
|
| 163 |
+
return $pyvenvConfig
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
<# Begin Activate script --------------------------------------------------- #>
|
| 168 |
+
|
| 169 |
+
# Determine the containing directory of this script
|
| 170 |
+
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
|
| 171 |
+
$VenvExecDir = Get-Item -Path $VenvExecPath
|
| 172 |
+
|
| 173 |
+
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
|
| 174 |
+
Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
|
| 175 |
+
Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
|
| 176 |
+
|
| 177 |
+
# Set values required in priority: CmdLine, ConfigFile, Default
|
| 178 |
+
# First, get the location of the virtual environment, it might not be
|
| 179 |
+
# VenvExecDir if specified on the command line.
|
| 180 |
+
if ($VenvDir) {
|
| 181 |
+
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
|
| 182 |
+
}
|
| 183 |
+
else {
|
| 184 |
+
Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
|
| 185 |
+
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
|
| 186 |
+
Write-Verbose "VenvDir=$VenvDir"
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
# Next, read the `pyvenv.cfg` file to determine any required value such
|
| 190 |
+
# as `prompt`.
|
| 191 |
+
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
|
| 192 |
+
|
| 193 |
+
# Next, set the prompt from the command line, or the config file, or
|
| 194 |
+
# just use the name of the virtual environment folder.
|
| 195 |
+
if ($Prompt) {
|
| 196 |
+
Write-Verbose "Prompt specified as argument, using '$Prompt'"
|
| 197 |
+
}
|
| 198 |
+
else {
|
| 199 |
+
Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
|
| 200 |
+
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
|
| 201 |
+
Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
|
| 202 |
+
$Prompt = $pyvenvCfg['prompt'];
|
| 203 |
+
}
|
| 204 |
+
else {
|
| 205 |
+
Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
|
| 206 |
+
Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
|
| 207 |
+
$Prompt = Split-Path -Path $venvDir -Leaf
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
Write-Verbose "Prompt = '$Prompt'"
|
| 212 |
+
Write-Verbose "VenvDir='$VenvDir'"
|
| 213 |
+
|
| 214 |
+
# Deactivate any currently active virtual environment, but leave the
|
| 215 |
+
# deactivate function in place.
|
| 216 |
+
deactivate -nondestructive
|
| 217 |
+
|
| 218 |
+
# Now set the environment variable VIRTUAL_ENV, used by many tools to determine
|
| 219 |
+
# that there is an activated venv.
|
| 220 |
+
$env:VIRTUAL_ENV = $VenvDir
|
| 221 |
+
|
| 222 |
+
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
|
| 223 |
+
|
| 224 |
+
Write-Verbose "Setting prompt to '$Prompt'"
|
| 225 |
+
|
| 226 |
+
# Set the prompt to include the env name
|
| 227 |
+
# Make sure _OLD_VIRTUAL_PROMPT is global
|
| 228 |
+
function global:_OLD_VIRTUAL_PROMPT { "" }
|
| 229 |
+
Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
|
| 230 |
+
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
|
| 231 |
+
|
| 232 |
+
function global:prompt {
|
| 233 |
+
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
|
| 234 |
+
_OLD_VIRTUAL_PROMPT
|
| 235 |
+
}
|
| 236 |
+
$env:VIRTUAL_ENV_PROMPT = $Prompt
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
# Clear PYTHONHOME
|
| 240 |
+
if (Test-Path -Path Env:PYTHONHOME) {
|
| 241 |
+
Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
|
| 242 |
+
Remove-Item -Path Env:PYTHONHOME
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
# Add the venv to the PATH
|
| 246 |
+
Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
|
| 247 |
+
$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"
|
grounding-dino/.eval_venv/bin/activate
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file must be used with "source bin/activate" *from bash*
|
| 2 |
+
# you cannot run it directly
|
| 3 |
+
|
| 4 |
+
deactivate () {
|
| 5 |
+
# reset old environment variables
|
| 6 |
+
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
|
| 7 |
+
PATH="${_OLD_VIRTUAL_PATH:-}"
|
| 8 |
+
export PATH
|
| 9 |
+
unset _OLD_VIRTUAL_PATH
|
| 10 |
+
fi
|
| 11 |
+
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
|
| 12 |
+
PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
|
| 13 |
+
export PYTHONHOME
|
| 14 |
+
unset _OLD_VIRTUAL_PYTHONHOME
|
| 15 |
+
fi
|
| 16 |
+
|
| 17 |
+
# Call hash to forget past commands. Without forgetting
|
| 18 |
+
# past commands the $PATH changes we made may not be respected
|
| 19 |
+
hash -r 2> /dev/null
|
| 20 |
+
|
| 21 |
+
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
|
| 22 |
+
PS1="${_OLD_VIRTUAL_PS1:-}"
|
| 23 |
+
export PS1
|
| 24 |
+
unset _OLD_VIRTUAL_PS1
|
| 25 |
+
fi
|
| 26 |
+
|
| 27 |
+
unset VIRTUAL_ENV
|
| 28 |
+
unset VIRTUAL_ENV_PROMPT
|
| 29 |
+
if [ ! "${1:-}" = "nondestructive" ] ; then
|
| 30 |
+
# Self destruct!
|
| 31 |
+
unset -f deactivate
|
| 32 |
+
fi
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
# unset irrelevant variables
|
| 36 |
+
deactivate nondestructive
|
| 37 |
+
|
| 38 |
+
VIRTUAL_ENV=/mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv
|
| 39 |
+
export VIRTUAL_ENV
|
| 40 |
+
|
| 41 |
+
_OLD_VIRTUAL_PATH="$PATH"
|
| 42 |
+
PATH="$VIRTUAL_ENV/"bin":$PATH"
|
| 43 |
+
export PATH
|
| 44 |
+
|
| 45 |
+
# unset PYTHONHOME if set
|
| 46 |
+
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
|
| 47 |
+
# could use `if (set -u; : $PYTHONHOME) ;` in bash
|
| 48 |
+
if [ -n "${PYTHONHOME:-}" ] ; then
|
| 49 |
+
_OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
|
| 50 |
+
unset PYTHONHOME
|
| 51 |
+
fi
|
| 52 |
+
|
| 53 |
+
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
|
| 54 |
+
_OLD_VIRTUAL_PS1="${PS1:-}"
|
| 55 |
+
PS1='(.eval_venv) '"${PS1:-}"
|
| 56 |
+
export PS1
|
| 57 |
+
VIRTUAL_ENV_PROMPT='(.eval_venv) '
|
| 58 |
+
export VIRTUAL_ENV_PROMPT
|
| 59 |
+
fi
|
| 60 |
+
|
| 61 |
+
# Call hash to forget past commands. Without forgetting
|
| 62 |
+
# past commands the $PATH changes we made may not be respected
|
| 63 |
+
hash -r 2> /dev/null
|
grounding-dino/.eval_venv/bin/activate.csh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file must be used with "source bin/activate.csh" *from csh*.
|
| 2 |
+
# You cannot run it directly.
|
| 3 |
+
# Created by Davide Di Blasi <davidedb@gmail.com>.
|
| 4 |
+
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
|
| 5 |
+
|
| 6 |
+
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate'
|
| 7 |
+
|
| 8 |
+
# Unset irrelevant variables.
|
| 9 |
+
deactivate nondestructive
|
| 10 |
+
|
| 11 |
+
setenv VIRTUAL_ENV /mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv
|
| 12 |
+
|
| 13 |
+
set _OLD_VIRTUAL_PATH="$PATH"
|
| 14 |
+
setenv PATH "$VIRTUAL_ENV/"bin":$PATH"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
set _OLD_VIRTUAL_PROMPT="$prompt"
|
| 18 |
+
|
| 19 |
+
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
|
| 20 |
+
set prompt = '(.eval_venv) '"$prompt"
|
| 21 |
+
setenv VIRTUAL_ENV_PROMPT '(.eval_venv) '
|
| 22 |
+
endif
|
| 23 |
+
|
| 24 |
+
alias pydoc python -m pydoc
|
| 25 |
+
|
| 26 |
+
rehash
|
grounding-dino/.eval_venv/bin/activate.fish
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file must be used with "source <venv>/bin/activate.fish" *from fish*
|
| 2 |
+
# (https://fishshell.com/); you cannot run it directly.
|
| 3 |
+
|
| 4 |
+
function deactivate -d "Exit virtual environment and return to normal shell environment"
|
| 5 |
+
# reset old environment variables
|
| 6 |
+
if test -n "$_OLD_VIRTUAL_PATH"
|
| 7 |
+
set -gx PATH $_OLD_VIRTUAL_PATH
|
| 8 |
+
set -e _OLD_VIRTUAL_PATH
|
| 9 |
+
end
|
| 10 |
+
if test -n "$_OLD_VIRTUAL_PYTHONHOME"
|
| 11 |
+
set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
|
| 12 |
+
set -e _OLD_VIRTUAL_PYTHONHOME
|
| 13 |
+
end
|
| 14 |
+
|
| 15 |
+
if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
|
| 16 |
+
set -e _OLD_FISH_PROMPT_OVERRIDE
|
| 17 |
+
# prevents error when using nested fish instances (Issue #93858)
|
| 18 |
+
if functions -q _old_fish_prompt
|
| 19 |
+
functions -e fish_prompt
|
| 20 |
+
functions -c _old_fish_prompt fish_prompt
|
| 21 |
+
functions -e _old_fish_prompt
|
| 22 |
+
end
|
| 23 |
+
end
|
| 24 |
+
|
| 25 |
+
set -e VIRTUAL_ENV
|
| 26 |
+
set -e VIRTUAL_ENV_PROMPT
|
| 27 |
+
if test "$argv[1]" != "nondestructive"
|
| 28 |
+
# Self-destruct!
|
| 29 |
+
functions -e deactivate
|
| 30 |
+
end
|
| 31 |
+
end
|
| 32 |
+
|
| 33 |
+
# Unset irrelevant variables.
|
| 34 |
+
deactivate nondestructive
|
| 35 |
+
|
| 36 |
+
set -gx VIRTUAL_ENV /mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv
|
| 37 |
+
|
| 38 |
+
set -gx _OLD_VIRTUAL_PATH $PATH
|
| 39 |
+
set -gx PATH "$VIRTUAL_ENV/"bin $PATH
|
| 40 |
+
|
| 41 |
+
# Unset PYTHONHOME if set.
|
| 42 |
+
if set -q PYTHONHOME
|
| 43 |
+
set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
|
| 44 |
+
set -e PYTHONHOME
|
| 45 |
+
end
|
| 46 |
+
|
| 47 |
+
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
|
| 48 |
+
# fish uses a function instead of an env var to generate the prompt.
|
| 49 |
+
|
| 50 |
+
# Save the current fish_prompt function as the function _old_fish_prompt.
|
| 51 |
+
functions -c fish_prompt _old_fish_prompt
|
| 52 |
+
|
| 53 |
+
# With the original prompt function renamed, we can override with our own.
|
| 54 |
+
function fish_prompt
|
| 55 |
+
# Save the return status of the last command.
|
| 56 |
+
set -l old_status $status
|
| 57 |
+
|
| 58 |
+
# Output the venv prompt; color taken from the blue of the Python logo.
|
| 59 |
+
printf "%s%s%s" (set_color 4B8BBE) '(.eval_venv) ' (set_color normal)
|
| 60 |
+
|
| 61 |
+
# Restore the return status of the previous command.
|
| 62 |
+
echo "exit $old_status" | .
|
| 63 |
+
# Output the original/"old" prompt.
|
| 64 |
+
_old_fish_prompt
|
| 65 |
+
end
|
| 66 |
+
|
| 67 |
+
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
|
| 68 |
+
set -gx VIRTUAL_ENV_PROMPT '(.eval_venv) '
|
| 69 |
+
end
|
grounding-dino/.eval_venv/bin/cygdb
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv/bin/python
|
| 2 |
+
import sys
|
| 3 |
+
from Cython.Debugger.Cygdb import main
|
| 4 |
+
if __name__ == '__main__':
|
| 5 |
+
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
| 6 |
+
sys.exit(main())
|
grounding-dino/.eval_venv/bin/cython
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv/bin/python
|
| 2 |
+
import sys
|
| 3 |
+
from Cython.Compiler.Main import setuptools_main
|
| 4 |
+
if __name__ == '__main__':
|
| 5 |
+
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
| 6 |
+
sys.exit(setuptools_main())
|
grounding-dino/.eval_venv/bin/cythonize
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv/bin/python
|
| 2 |
+
import sys
|
| 3 |
+
from Cython.Build.Cythonize import main
|
| 4 |
+
if __name__ == '__main__':
|
| 5 |
+
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
| 6 |
+
sys.exit(main())
|
grounding-dino/.eval_venv/bin/f2py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv/bin/python
|
| 2 |
+
import sys
|
| 3 |
+
from numpy.f2py.f2py2e import main
|
| 4 |
+
if __name__ == '__main__':
|
| 5 |
+
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
| 6 |
+
sys.exit(main())
|
grounding-dino/.eval_venv/bin/pip
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv/bin/python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import re
|
| 4 |
+
import sys
|
| 5 |
+
from pip._internal.cli.main import main
|
| 6 |
+
if __name__ == '__main__':
|
| 7 |
+
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
| 8 |
+
sys.exit(main())
|
grounding-dino/.eval_venv/bin/pip3
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv/bin/python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import re
|
| 4 |
+
import sys
|
| 5 |
+
from pip._internal.cli.main import main
|
| 6 |
+
if __name__ == '__main__':
|
| 7 |
+
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
| 8 |
+
sys.exit(main())
|
grounding-dino/.eval_venv/bin/pip3.11
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv/bin/python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import re
|
| 4 |
+
import sys
|
| 5 |
+
from pip._internal.cli.main import main
|
| 6 |
+
if __name__ == '__main__':
|
| 7 |
+
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
| 8 |
+
sys.exit(main())
|
grounding-dino/.eval_venv/bin/wgit
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv/bin/python
|
| 2 |
+
import sys
|
| 3 |
+
from fairscale.experimental.wgit.__main__ import main
|
| 4 |
+
if __name__ == '__main__':
|
| 5 |
+
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
| 6 |
+
sys.exit(main())
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/__editable___mmdet_3_3_0_finder.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys
|
| 3 |
+
from importlib.machinery import ModuleSpec, PathFinder
|
| 4 |
+
from importlib.machinery import all_suffixes as module_suffixes
|
| 5 |
+
from importlib.util import spec_from_file_location
|
| 6 |
+
from itertools import chain
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
MAPPING: dict[str, str] = {'mmdet': '/mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/mmdetection/mmdet'}
|
| 10 |
+
NAMESPACES: dict[str, list[str]] = {}
|
| 11 |
+
PATH_PLACEHOLDER = '__editable__.mmdet-3.3.0.finder' + ".__path_hook__"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class _EditableFinder: # MetaPathFinder
|
| 15 |
+
@classmethod
|
| 16 |
+
def find_spec(cls, fullname: str, path=None, target=None) -> ModuleSpec | None: # type: ignore
|
| 17 |
+
# Top-level packages and modules (we know these exist in the FS)
|
| 18 |
+
if fullname in MAPPING:
|
| 19 |
+
pkg_path = MAPPING[fullname]
|
| 20 |
+
return cls._find_spec(fullname, Path(pkg_path))
|
| 21 |
+
|
| 22 |
+
# Handle immediate children modules (required for namespaces to work)
|
| 23 |
+
# To avoid problems with case sensitivity in the file system we delegate
|
| 24 |
+
# to the importlib.machinery implementation.
|
| 25 |
+
parent, _, child = fullname.rpartition(".")
|
| 26 |
+
if parent and parent in MAPPING:
|
| 27 |
+
return PathFinder.find_spec(fullname, path=[MAPPING[parent]])
|
| 28 |
+
|
| 29 |
+
# Other levels of nesting should be handled automatically by importlib
|
| 30 |
+
# using the parent path.
|
| 31 |
+
return None
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def _find_spec(cls, fullname: str, candidate_path: Path) -> ModuleSpec | None:
|
| 35 |
+
init = candidate_path / "__init__.py"
|
| 36 |
+
candidates = (candidate_path.with_suffix(x) for x in module_suffixes())
|
| 37 |
+
for candidate in chain([init], candidates):
|
| 38 |
+
if candidate.exists():
|
| 39 |
+
return spec_from_file_location(fullname, candidate)
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class _EditableNamespaceFinder: # PathEntryFinder
|
| 44 |
+
@classmethod
|
| 45 |
+
def _path_hook(cls, path) -> type[_EditableNamespaceFinder]:
|
| 46 |
+
if path == PATH_PLACEHOLDER:
|
| 47 |
+
return cls
|
| 48 |
+
raise ImportError
|
| 49 |
+
|
| 50 |
+
@classmethod
|
| 51 |
+
def _paths(cls, fullname: str) -> list[str]:
|
| 52 |
+
paths = NAMESPACES[fullname]
|
| 53 |
+
if not paths and fullname in MAPPING:
|
| 54 |
+
paths = [MAPPING[fullname]]
|
| 55 |
+
# Always add placeholder, for 2 reasons:
|
| 56 |
+
# 1. __path__ cannot be empty for the spec to be considered namespace.
|
| 57 |
+
# 2. In the case of nested namespaces, we need to force
|
| 58 |
+
# import machinery to query _EditableNamespaceFinder again.
|
| 59 |
+
return [*paths, PATH_PLACEHOLDER]
|
| 60 |
+
|
| 61 |
+
@classmethod
|
| 62 |
+
def find_spec(cls, fullname: str, target=None) -> ModuleSpec | None: # type: ignore
|
| 63 |
+
if fullname in NAMESPACES:
|
| 64 |
+
spec = ModuleSpec(fullname, None, is_package=True)
|
| 65 |
+
spec.submodule_search_locations = cls._paths(fullname)
|
| 66 |
+
return spec
|
| 67 |
+
return None
|
| 68 |
+
|
| 69 |
+
@classmethod
|
| 70 |
+
def find_module(cls, _fullname) -> None:
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def install():
|
| 75 |
+
if not any(finder == _EditableFinder for finder in sys.meta_path):
|
| 76 |
+
sys.meta_path.append(_EditableFinder)
|
| 77 |
+
|
| 78 |
+
if not NAMESPACES:
|
| 79 |
+
return
|
| 80 |
+
|
| 81 |
+
if not any(hook == _EditableNamespaceFinder._path_hook for hook in sys.path_hooks):
|
| 82 |
+
# PathEntryFinder is needed to create NamespaceSpec without private APIS
|
| 83 |
+
sys.path_hooks.append(_EditableNamespaceFinder._path_hook)
|
| 84 |
+
if PATH_PLACEHOLDER not in sys.path:
|
| 85 |
+
sys.path.append(PATH_PLACEHOLDER) # Used just to trigger the path hook
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/__pycache__/fsdp.cpython-311.pyc
ADDED
|
Binary file (22.6 kB). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/__pycache__/moe.cpython-311.pyc
ADDED
|
Binary file (7.33 kB). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/__pycache__/oss.cpython-311.pyc
ADDED
|
Binary file (21.5 kB). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/__pycache__/utils.cpython-311.pyc
ADDED
|
Binary file (10.1 kB). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (261 Bytes). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/__pycache__/mnist.cpython-311.pyc
ADDED
|
Binary file (1.72 kB). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/__pycache__/wikitext2_data.cpython-311.pyc
ADDED
|
Binary file (6.71 kB). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/mnist.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import shutil
|
| 9 |
+
import tempfile
|
| 10 |
+
|
| 11 |
+
from torchvision.datasets import MNIST
|
| 12 |
+
|
| 13 |
+
TEMPDIR = tempfile.gettempdir()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def setup_cached_mnist():
|
| 17 |
+
done, tentatives = False, 0
|
| 18 |
+
while not done and tentatives < 5:
|
| 19 |
+
# Monkey patch the resource URLs to work around a possible blacklist
|
| 20 |
+
MNIST.mirrors = ["https://github.com/blefaudeux/mnist_dataset/raw/main/"] + MNIST.mirrors
|
| 21 |
+
|
| 22 |
+
# This will automatically skip the download if the dataset is already there, and check the checksum
|
| 23 |
+
try:
|
| 24 |
+
_ = MNIST(transform=None, download=True, root=TEMPDIR)
|
| 25 |
+
done = True
|
| 26 |
+
except RuntimeError as e:
|
| 27 |
+
logging.warning(e)
|
| 28 |
+
mnist_root = Path(TEMPDIR + "/MNIST")
|
| 29 |
+
# Corrupted data, erase and restart
|
| 30 |
+
shutil.rmtree(str(mnist_root))
|
| 31 |
+
|
| 32 |
+
tentatives += 1
|
| 33 |
+
|
| 34 |
+
if done is False:
|
| 35 |
+
logging.error("Could not download MNIST dataset")
|
| 36 |
+
exit(-1)
|
| 37 |
+
else:
|
| 38 |
+
logging.info("Dataset downloaded")
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/datasets/wikitext2_data.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
from collections import namedtuple
|
| 7 |
+
from distutils.version import LooseVersion
|
| 8 |
+
import io
|
| 9 |
+
import operator
|
| 10 |
+
import tempfile
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch.utils.data import DataLoader
|
| 14 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 15 |
+
import torchtext
|
| 16 |
+
from torchtext.data.utils import get_tokenizer
|
| 17 |
+
from torchtext.utils import download_from_url, extract_archive
|
| 18 |
+
|
| 19 |
+
if operator.ge(torchtext.__version__, LooseVersion("0.10.0")):
|
| 20 |
+
from torchtext.legacy.vocab import build_vocab_from_iterator
|
| 21 |
+
else:
|
| 22 |
+
from torchtext.vocab import build_vocab_from_iterator
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _batchify(data, batch_size):
|
| 26 |
+
data = torch.tensor(data)
|
| 27 |
+
# Divide the dataset into bsz parts.
|
| 28 |
+
nbatch = data.size(0) // batch_size
|
| 29 |
+
# Trim off any extra elements that wouldn't cleanly fit (remainders).
|
| 30 |
+
data = data.narrow(0, 0, nbatch * batch_size)
|
| 31 |
+
# Evenly divide the data across the bsz batches.
|
| 32 |
+
data = data.view(batch_size, -1).t().contiguous()
|
| 33 |
+
return data
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _get_total_batch_size(benchmark_config, model_specs):
|
| 37 |
+
return model_specs["seq_len"] * benchmark_config["batch_size"]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
DatasetsInfo = namedtuple("DataSetsInfo", ["ntokens", "train_dataset", "valid_dataset", "test_dataset"])
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def get_real_datasets():
|
| 44 |
+
url = "https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-v1.zip"
|
| 45 |
+
tmpdir = tempfile.TemporaryDirectory()
|
| 46 |
+
test_filepath, valid_filepath, train_filepath = extract_archive(download_from_url(url, root=tmpdir.name))
|
| 47 |
+
tokenizer = get_tokenizer("basic_english")
|
| 48 |
+
|
| 49 |
+
def data_process(raw_text_iter):
|
| 50 |
+
data = [torch.tensor([vocab[token] for token in tokenizer(item)], dtype=torch.long) for item in raw_text_iter]
|
| 51 |
+
return torch.cat(tuple(filter(lambda t: t.numel() > 0, data)))
|
| 52 |
+
|
| 53 |
+
vocab = build_vocab_from_iterator(map(tokenizer, iter(io.open(train_filepath, encoding="utf8"))))
|
| 54 |
+
|
| 55 |
+
train_dataset = data_process(iter(io.open(train_filepath, encoding="utf8")))
|
| 56 |
+
valid_dataset = data_process(iter(io.open(valid_filepath, encoding="utf8")))
|
| 57 |
+
test_dataset = data_process(iter(io.open(test_filepath, encoding="utf8")))
|
| 58 |
+
return DatasetsInfo(len(vocab.stoi), train_dataset, valid_dataset, test_dataset)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def get_dataloaders(datasets_info, benchmark_config, model_specs, num_replicas=1, rank=0):
|
| 62 |
+
ntokens, train_dataset, valid_dataset, test_dataset = datasets_info
|
| 63 |
+
|
| 64 |
+
def batchify(data):
|
| 65 |
+
batch_size = benchmark_config["batch_size"]
|
| 66 |
+
return _batchify(data, batch_size)
|
| 67 |
+
|
| 68 |
+
total_batch_size = _get_total_batch_size(benchmark_config, model_specs)
|
| 69 |
+
train_dataloader = DataLoader(
|
| 70 |
+
train_dataset,
|
| 71 |
+
sampler=DistributedSampler(train_dataset, num_replicas=num_replicas, rank=rank),
|
| 72 |
+
batch_size=total_batch_size,
|
| 73 |
+
collate_fn=batchify,
|
| 74 |
+
)
|
| 75 |
+
valid_dataloader = DataLoader(
|
| 76 |
+
valid_dataset,
|
| 77 |
+
sampler=DistributedSampler(valid_dataset, num_replicas=num_replicas, rank=rank),
|
| 78 |
+
batch_size=total_batch_size,
|
| 79 |
+
collate_fn=batchify,
|
| 80 |
+
)
|
| 81 |
+
test_dataloader = DataLoader(
|
| 82 |
+
test_dataset,
|
| 83 |
+
sampler=DistributedSampler(test_dataset, num_replicas=num_replicas, rank=rank),
|
| 84 |
+
batch_size=total_batch_size,
|
| 85 |
+
collate_fn=batchify,
|
| 86 |
+
)
|
| 87 |
+
return train_dataloader, valid_dataloader, test_dataloader
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def get_real_dataloaders(args, benchmark_config, model_specs, num_replicas=1, rank=0):
|
| 91 |
+
"""Return real dataloaders for training, testing and validation."""
|
| 92 |
+
dataset_info = get_real_datasets()
|
| 93 |
+
train_dataloader, valid_dataloader, test_dataloader = get_dataloaders(
|
| 94 |
+
dataset_info, benchmark_config, model_specs, num_replicas, rank
|
| 95 |
+
)
|
| 96 |
+
return dataset_info.ntokens, train_dataloader, valid_dataloder, test_dataloader
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_synthetic_datasets():
|
| 100 |
+
# vocab_size is 10000 and length of the real data is 2049990.
|
| 101 |
+
lm_dataset = torch.randint(1, 10000, (2049990,))
|
| 102 |
+
return DatasetsInfo(10000, lm_dataset, lm_dataset, lm_dataset)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def get_synthetic_dataloaders(args, benchmark_config, model_specs, num_replicas=1, rank=0):
|
| 106 |
+
"""Return synthetic dataloaders for training, testing and validation."""
|
| 107 |
+
return get_dataloaders(get_synthetic_datasets(), benchmark_config, model_specs, num_replicas, rank)
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/fsdp.py
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from functools import reduce
|
| 9 |
+
import gc
|
| 10 |
+
import logging
|
| 11 |
+
import math
|
| 12 |
+
import operator
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
from datasets.wikitext2_data import get_real_dataloaders as get_real_wikitext2_dataloaders
|
| 16 |
+
from datasets.wikitext2_data import get_synthetic_dataloaders as get_synthetic_wikitext2_dataloaders
|
| 17 |
+
from models import transformer_lm
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
import torch.distributed as dist
|
| 21 |
+
import torch.multiprocessing as mp
|
| 22 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 23 |
+
from torch.optim import Adam
|
| 24 |
+
|
| 25 |
+
from benchmarks.golden_configs.lm_wikitext2 import FSDP as lm_wikitext2
|
| 26 |
+
from fairscale.nn import auto_wrap, default_auto_wrap_policy, enable_wrap
|
| 27 |
+
from fairscale.nn.data_parallel import FullyShardedDataParallel as FSDP
|
| 28 |
+
|
| 29 |
+
RPC_PORT = 29501
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def verify_peak_memory(rank, golden_config, std_dev):
|
| 33 |
+
logging.debug(
|
| 34 |
+
"Peak allocated bytes on cuda:0: {:1d}".format(torch.cuda.memory_stats(rank)["allocated_bytes.all.peak"])
|
| 35 |
+
)
|
| 36 |
+
current_device_usage = torch.cuda.memory_stats(rank)["allocated_bytes.all.peak"]
|
| 37 |
+
golden_ref = golden_config["peak_mem_usage"][rank]
|
| 38 |
+
if not current_device_usage < golden_ref * std_dev:
|
| 39 |
+
raise RuntimeError(
|
| 40 |
+
"Peak memory usage for cuda device {:d} is {:d} which"
|
| 41 |
+
"is less than golden reference value of {:d}".format(rank, current_device_usage, golden_ref)
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def verify_lm_run(wps, golden_config, args):
|
| 46 |
+
"""Verify that words per second for a given benchmark run matches the golden data."""
|
| 47 |
+
|
| 48 |
+
if torch.distributed.get_rank() == 0:
|
| 49 |
+
# Assert that words per second is within 3 standard deviations of the average
|
| 50 |
+
# of five golden runs
|
| 51 |
+
logging.info("Throughput(wps) is {:.2f}.".format(wps))
|
| 52 |
+
if not wps > (golden_config["avg_wps"] - (3 * golden_config["std_dev_wps"])):
|
| 53 |
+
raise RuntimeError(
|
| 54 |
+
"Throughput(wps):{:.2f} is below the golden threshold of an "
|
| 55 |
+
"average value of {:.2f} and standard dev of {:.2f}.".format(
|
| 56 |
+
wps, golden_config["avg_wps"], golden_config["std_dev_wps"]
|
| 57 |
+
)
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
for i in range(torch.cuda.device_count()):
|
| 61 |
+
verify_peak_memory(i, golden_config, 1.1)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def init_random_seed(seed: int):
|
| 65 |
+
|
| 66 |
+
torch.manual_seed(seed)
|
| 67 |
+
torch.cuda.manual_seed(seed)
|
| 68 |
+
np.random.seed(seed)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def get_model_and_optimizer(args, device, benchmark_config, model_config):
|
| 72 |
+
"""Return instantiated model and optimizer function."""
|
| 73 |
+
|
| 74 |
+
if args.model_name == "lm":
|
| 75 |
+
model = get_lm_model(args, device, model_config)
|
| 76 |
+
|
| 77 |
+
lr = benchmark_config["lr"]
|
| 78 |
+
|
| 79 |
+
def make_adam(params):
|
| 80 |
+
return Adam(params, lr=lr)
|
| 81 |
+
|
| 82 |
+
optimizer = make_adam
|
| 83 |
+
return model, optimizer
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def get_lm_model(args, device, config):
|
| 87 |
+
"""Get language model(based on GPT-2) used for sequence prediction."""
|
| 88 |
+
|
| 89 |
+
ninp = config["ninp"]
|
| 90 |
+
nhead = config["nhead"]
|
| 91 |
+
initrange = config["initrange"]
|
| 92 |
+
dropout = config["dropout"]
|
| 93 |
+
vocab_size = config["vocab_size"]
|
| 94 |
+
nhid = config["nhid"]
|
| 95 |
+
ndecoder = config["num_decoder_layers"]
|
| 96 |
+
|
| 97 |
+
return transformer_lm.TransformerLM(vocab_size, ninp, nhead, nhid, dropout, initrange, ndecoder).to(device)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def get_tensors_by_size_bucket():
|
| 101 |
+
|
| 102 |
+
size_buckets = defaultdict(int)
|
| 103 |
+
for obj in gc.get_objects():
|
| 104 |
+
if not isinstance(obj, torch.Tensor):
|
| 105 |
+
continue
|
| 106 |
+
if obj.device.type == "cuda":
|
| 107 |
+
size_buckets[(*obj.size(),) + (obj.element_size(),)] += 1
|
| 108 |
+
|
| 109 |
+
return size_buckets
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def log_number_of_parameters(model):
|
| 113 |
+
|
| 114 |
+
num_params = reduce(operator.add, (reduce(operator.mul, x.size()) for x in model.parameters()))
|
| 115 |
+
if hasattr(model, "group"):
|
| 116 |
+
total = torch.Tensor([num_params])
|
| 117 |
+
if torch.cuda.is_available():
|
| 118 |
+
total = total.cuda()
|
| 119 |
+
torch.distributed.all_reduce(total, group=model.group)
|
| 120 |
+
print(
|
| 121 |
+
f"training model, #params = {num_params/10**6}M, group: {model.group.rank()}, grank:"
|
| 122 |
+
f" {torch.distributed.get_rank()}, sizes {model.group.size()}"
|
| 123 |
+
)
|
| 124 |
+
torch.distributed.barrier()
|
| 125 |
+
if model.group.rank() == 0:
|
| 126 |
+
print(f"total #prams = {total.item()}")
|
| 127 |
+
else:
|
| 128 |
+
print(f"training model, #params = {num_params/10**6}M")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def get_device(model, index):
|
| 132 |
+
if isinstance(model, DDP):
|
| 133 |
+
model = model.module
|
| 134 |
+
|
| 135 |
+
if not torch.cuda.is_available():
|
| 136 |
+
return torch.device("cpu")
|
| 137 |
+
if hasattr(model, "devices"):
|
| 138 |
+
return model.devices[index]
|
| 139 |
+
else:
|
| 140 |
+
return torch.cuda.current_device()
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def get_fake_dataloader(lm_dataloader_len, args):
|
| 144 |
+
fake_input = {"input": torch.zeros(args.batch_size)}
|
| 145 |
+
|
| 146 |
+
class FakeDataset:
|
| 147 |
+
def __getitem__(self, index):
|
| 148 |
+
return fake_input
|
| 149 |
+
|
| 150 |
+
def __len__(self):
|
| 151 |
+
return lm_dataloader_len
|
| 152 |
+
|
| 153 |
+
return FakeDataset()
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def train(model_config, model, benchmark_config, model_specs, args):
|
| 157 |
+
lm_dataloader, _, _ = model_config["data"]
|
| 158 |
+
criterion = benchmark_config["criterion"]
|
| 159 |
+
vocab_size = model_specs["vocab_size"]
|
| 160 |
+
optimizer = model_config["optimizer"]
|
| 161 |
+
|
| 162 |
+
if not args.benchmark_eval:
|
| 163 |
+
model.train()
|
| 164 |
+
log_number_of_parameters(model)
|
| 165 |
+
|
| 166 |
+
total_loss = 0.0
|
| 167 |
+
word_counter = 0
|
| 168 |
+
|
| 169 |
+
optimizer = optimizer(model.parameters())
|
| 170 |
+
|
| 171 |
+
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
| 172 |
+
|
| 173 |
+
total_tokens = 0
|
| 174 |
+
total_tokens_per_log_interval = 0
|
| 175 |
+
bptt = 2
|
| 176 |
+
start_time = time.time()
|
| 177 |
+
epoch_start_time = 0.0
|
| 178 |
+
|
| 179 |
+
def get_batch(source):
|
| 180 |
+
seq_len = len(source) - 1
|
| 181 |
+
data = source[0:seq_len]
|
| 182 |
+
target = source[1 : 1 + seq_len]
|
| 183 |
+
return data, target
|
| 184 |
+
|
| 185 |
+
for i, batch in enumerate(lm_dataloader):
|
| 186 |
+
if i == 1:
|
| 187 |
+
epoch_start_time = time.time()
|
| 188 |
+
|
| 189 |
+
source, target = get_batch(batch)
|
| 190 |
+
if args.full_fp16:
|
| 191 |
+
# source = source.half()
|
| 192 |
+
target = target.half()
|
| 193 |
+
if args.max_batch and i > args.max_batch:
|
| 194 |
+
break
|
| 195 |
+
|
| 196 |
+
if i > 0:
|
| 197 |
+
total_tokens += source.numel()
|
| 198 |
+
|
| 199 |
+
if args.benchmark_eval:
|
| 200 |
+
input = source.cuda()
|
| 201 |
+
target = target.cuda()
|
| 202 |
+
output = model(input)
|
| 203 |
+
print(f"output.dtype {output.dtype}, target.dtype {target.dtype}")
|
| 204 |
+
loss = torch.nn.CrossEntropyLoss()(output.view(-1, vocab_size), target.view(-1))
|
| 205 |
+
else:
|
| 206 |
+
optimizer.zero_grad()
|
| 207 |
+
input = source.cuda()
|
| 208 |
+
target = target.cuda()
|
| 209 |
+
output = model(input)
|
| 210 |
+
|
| 211 |
+
loss = criterion(output.view(-1, vocab_size), target.view(-1))
|
| 212 |
+
loss.backward()
|
| 213 |
+
|
| 214 |
+
torch.nn.utils.clip_grad_value_(model.parameters(), model_specs["clip_value"])
|
| 215 |
+
optimizer.step()
|
| 216 |
+
|
| 217 |
+
total_loss += loss.item()
|
| 218 |
+
|
| 219 |
+
log_interval = 1
|
| 220 |
+
total_tokens_per_log_interval += source.numel()
|
| 221 |
+
if i % log_interval == 0 and i > 0:
|
| 222 |
+
cur_loss = total_loss / log_interval
|
| 223 |
+
elapsed = time.time() - start_time
|
| 224 |
+
if dist.get_rank() == 0:
|
| 225 |
+
print(
|
| 226 |
+
"| batch {:5d} | wps {:5.2f} | loss {:5.2f} | ppl {:8.2f}".format(
|
| 227 |
+
i, total_tokens_per_log_interval / elapsed, cur_loss, math.exp(cur_loss)
|
| 228 |
+
)
|
| 229 |
+
)
|
| 230 |
+
total_tokens_per_log_interval = 0
|
| 231 |
+
total_loss = 0
|
| 232 |
+
start_time = time.time()
|
| 233 |
+
|
| 234 |
+
if epoch_start_time != 0:
|
| 235 |
+
torch.cuda.synchronize()
|
| 236 |
+
wps = total_tokens / (time.time() - epoch_start_time)
|
| 237 |
+
else:
|
| 238 |
+
raise RuntimeError(
|
| 239 |
+
"Unable to benchmark on a single batch. Increase the size " " of the dataset and rerun the benchmark."
|
| 240 |
+
)
|
| 241 |
+
return wps, loss.item()
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def get_number_of_words(data):
|
| 245 |
+
return data.size()[0] * data.size()[1]
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def benchmark_language_model(model_config, model, benchmark_config, model_specs, args):
|
| 249 |
+
golden_config = get_golden_config(args.model_name, args)
|
| 250 |
+
epoch = benchmark_config["epochs"]
|
| 251 |
+
start_time = time.time()
|
| 252 |
+
if dist.get_rank() == 0:
|
| 253 |
+
print("-" * 110)
|
| 254 |
+
print("| start of epoch {:1d}".format(epoch))
|
| 255 |
+
print("-" * 110)
|
| 256 |
+
wps, loss = train(model_config, model, benchmark_config, model_specs, args)
|
| 257 |
+
elapsed_time = time.time() - start_time
|
| 258 |
+
if dist.get_rank() == 0:
|
| 259 |
+
print("-" * 110)
|
| 260 |
+
print("| end of epoch {:1d} | time: {:5.2f}s | train loss {:5.2f} ".format(epoch, elapsed_time, loss))
|
| 261 |
+
print("-" * 110)
|
| 262 |
+
print("Throughput(wps) is {:.2f}.".format(wps))
|
| 263 |
+
print(
|
| 264 |
+
"Peak allocated bytes on cuda:{}: {:4f}GB".format(
|
| 265 |
+
dist.get_rank(), torch.cuda.memory_stats(dist.get_rank())["allocated_bytes.all.peak"] / 2**30
|
| 266 |
+
)
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
verify_lm_run(wps, golden_config, args)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def get_synthetic_dataloaders(args, device, benchmark_config, model_specs):
|
| 273 |
+
"""Returns dataloader for synthetic data."""
|
| 274 |
+
|
| 275 |
+
if args.model_name == "lm":
|
| 276 |
+
return get_synthetic_wikitext2_dataloaders(args, benchmark_config, model_specs)
|
| 277 |
+
else:
|
| 278 |
+
raise RuntimeError("Unrecognized args.model_mame " % args.model_name)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def get_real_dataloaders(args, device, benchmark_config, model_specs):
|
| 282 |
+
"""Returns dataloaders for real data."""
|
| 283 |
+
|
| 284 |
+
if args.model_name == "lm":
|
| 285 |
+
data = get_real_wikitext2_dataloaders(args, benchmark_config, model_specs)
|
| 286 |
+
ntokens, train_dataloader, valid_dataloader, test_dataloader = data
|
| 287 |
+
model_specs["vocab_size"] = ntokens
|
| 288 |
+
return train_dataloader, valid_dataloader, test_dataloader
|
| 289 |
+
else:
|
| 290 |
+
raise RuntimeError("Unrecognized args.model_mame " % args.model_name)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def create_model_config(args, benchmark_config=None, model_specs=None):
|
| 294 |
+
"""Return a dict with the given model, dataset and optimizer."""
|
| 295 |
+
|
| 296 |
+
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
| 297 |
+
|
| 298 |
+
if args.use_synthetic_data:
|
| 299 |
+
dataloader_fn = get_synthetic_dataloaders
|
| 300 |
+
else:
|
| 301 |
+
dataloader_fn = get_real_dataloaders
|
| 302 |
+
|
| 303 |
+
data = dataloader_fn(args, device, benchmark_config, model_specs)
|
| 304 |
+
model, optimizer = get_model_and_optimizer(args, device, benchmark_config, model_specs)
|
| 305 |
+
return {
|
| 306 |
+
"model": model,
|
| 307 |
+
"optimizer": optimizer,
|
| 308 |
+
"data": data,
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def create_benchmark_config(model_name):
|
| 313 |
+
"""Return a dict with configurations required for benchmarking `model_name` model."""
|
| 314 |
+
|
| 315 |
+
if model_name == "lm":
|
| 316 |
+
return lm_wikitext2.get_benchmark_config()
|
| 317 |
+
else:
|
| 318 |
+
raise RuntimeError("Unrecognized args.model_mame " % args.model_name)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def get_model_specs(model_name):
|
| 322 |
+
"""Return a dict with configurations required for configuring `model_name` model."""
|
| 323 |
+
|
| 324 |
+
if model_name == "lm":
|
| 325 |
+
return lm_wikitext2.get_model_config()
|
| 326 |
+
else:
|
| 327 |
+
raise RuntimeError("Unrecognized args.model_mame " % args.model_name)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def get_golden_config(model_name, args):
|
| 331 |
+
"""Return a dict with the golden data for throughput and memory usage."""
|
| 332 |
+
|
| 333 |
+
if model_name == "lm":
|
| 334 |
+
return lm_wikitext2.get_golden_synthetic_stats()
|
| 335 |
+
else:
|
| 336 |
+
raise RuntimeError("Unrecognized args.model_mame " % args.model_name)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def benchmark_fsdp(rank, args, world_size):
|
| 340 |
+
"""Benchmark a given model using a single process and multiple devices."""
|
| 341 |
+
|
| 342 |
+
init_method_pgroup = "tcp://localhost:{}".format(RPC_PORT)
|
| 343 |
+
torch.distributed.init_process_group(
|
| 344 |
+
backend="nccl", rank=rank, world_size=world_size, init_method=init_method_pgroup
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
torch.cuda.set_device(rank)
|
| 348 |
+
init_random_seed(0)
|
| 349 |
+
logging.basicConfig(level=logging.DEBUG)
|
| 350 |
+
|
| 351 |
+
benchmark_config = create_benchmark_config(args.model_name)
|
| 352 |
+
model_specs = get_model_specs(args.model_name)
|
| 353 |
+
model_config = create_model_config(args, benchmark_config=benchmark_config, model_specs=model_specs)
|
| 354 |
+
model = model_config["model"]
|
| 355 |
+
config = {}
|
| 356 |
+
|
| 357 |
+
if args.full_fp16:
|
| 358 |
+
config["compute_dtype"] = torch.float16
|
| 359 |
+
config["mixed_precision"] = False
|
| 360 |
+
|
| 361 |
+
if args.enable_auto_wrap:
|
| 362 |
+
with enable_wrap(wrapper_cls=FSDP, **config):
|
| 363 |
+
fsdp_model = auto_wrap(model, auto_wrap_policy=default_auto_wrap_policy)
|
| 364 |
+
fsdp_model = FSDP(fsdp_model, **config)
|
| 365 |
+
else:
|
| 366 |
+
fsdp_model = FSDP(model, **config)
|
| 367 |
+
|
| 368 |
+
if args.full_fp16:
|
| 369 |
+
fsdp_model = fsdp_model.half()
|
| 370 |
+
print(f"param dtype {[p.dtype for p in fsdp_model.parameters()]}")
|
| 371 |
+
if args.dry_run:
|
| 372 |
+
train(model_config, fsdp_model, benchmark_config, model_specs, args)
|
| 373 |
+
else:
|
| 374 |
+
benchmark_language_model(model_config, fsdp_model, benchmark_config, model_specs, args)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
parser = argparse.ArgumentParser(description="benchmark")
|
| 378 |
+
parser.add_argument("--max_batch", type=int, default=4, help="Max number of batches")
|
| 379 |
+
parser.add_argument("--use_synthetic_data", action="store_true", help="Uses synthetic data for running benchmarks.")
|
| 380 |
+
parser.add_argument("--dry_run", action="store_true", help="Run a sample training run without regression testing.")
|
| 381 |
+
parser.add_argument(
|
| 382 |
+
"--model_name",
|
| 383 |
+
default="lm",
|
| 384 |
+
help="Language Model(LM) used to benchmark FSDP.",
|
| 385 |
+
)
|
| 386 |
+
parser.add_argument("--debug", action="store_true", default=False, help="Display additional debug information")
|
| 387 |
+
parser.add_argument("--enable_auto_wrap", action="store_true", default=False, help="Use auto_wrap with FSDP")
|
| 388 |
+
parser.add_argument("--benchmark_eval", action="store_true", default=False, help="Benchmark evaluation workflow.")
|
| 389 |
+
parser.add_argument("--full_fp16", action="store_true", default=False, help="Benchmark in full fp16 mode.")
|
| 390 |
+
|
| 391 |
+
if __name__ == "__main__":
|
| 392 |
+
args = parser.parse_args()
|
| 393 |
+
logging.basicConfig(level=logging.DEBUG)
|
| 394 |
+
|
| 395 |
+
print(f"Running FSDP benchmark with args: {args}")
|
| 396 |
+
num_devices = torch.cuda.device_count() if torch.cuda.is_available() else 1
|
| 397 |
+
assert num_devices > 0
|
| 398 |
+
|
| 399 |
+
mp.spawn(
|
| 400 |
+
benchmark_fsdp,
|
| 401 |
+
args=(args, num_devices),
|
| 402 |
+
nprocs=num_devices,
|
| 403 |
+
join=True,
|
| 404 |
+
)
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (267 Bytes). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/__pycache__/lm_wikitext2.cpython-311.pyc
ADDED
|
Binary file (5.24 kB). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/__pycache__/oss_mnist.cpython-311.pyc
ADDED
|
Binary file (736 Bytes). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/lm_wikitext2.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
|
| 8 |
+
from fairscale.optim import GradScaler
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Offload_Transformer:
|
| 12 |
+
def get_model_config():
|
| 13 |
+
return {
|
| 14 |
+
"vocab_size": 10000,
|
| 15 |
+
"ninp": 2048, # embedding dimension
|
| 16 |
+
"nhid": 2048, # the dimension of the feedforward network model in nn.TransformerEncoder
|
| 17 |
+
"nhead": 32, # the number of heads in the multiheadattention models
|
| 18 |
+
"dropout": 0,
|
| 19 |
+
"initrange": 0.1,
|
| 20 |
+
"scaler": GradScaler(),
|
| 21 |
+
"clip_value": 0.05,
|
| 22 |
+
"num_decoder_layers": 10,
|
| 23 |
+
"seq_len": 32,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
def get_benchmark_config(checkpoint_activation=True):
|
| 27 |
+
|
| 28 |
+
return {
|
| 29 |
+
"epochs": 1,
|
| 30 |
+
"lr": 0.001, # learning rate
|
| 31 |
+
"batch_size": 8,
|
| 32 |
+
"criterion": nn.CrossEntropyLoss(),
|
| 33 |
+
"checkpoint_activation": checkpoint_activation,
|
| 34 |
+
"num_microbatches": 1,
|
| 35 |
+
"slices": 3,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
def get_golden_real_stats():
|
| 39 |
+
return {
|
| 40 |
+
"avg_wps": 192.105,
|
| 41 |
+
"std_dev_wps": 39.56,
|
| 42 |
+
"peak_mem_usage": 1180848128,
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Offload_Sequential:
|
| 47 |
+
def get_model_config():
|
| 48 |
+
return {
|
| 49 |
+
"inputs": 100,
|
| 50 |
+
"outputs": 5,
|
| 51 |
+
"hidden": 1000,
|
| 52 |
+
"layers": 100,
|
| 53 |
+
"clip_value": 0.05,
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
def get_benchmark_config():
|
| 57 |
+
|
| 58 |
+
return {
|
| 59 |
+
"epochs": 1,
|
| 60 |
+
"lr": 0.001, # learning rate
|
| 61 |
+
"batch_size": 8,
|
| 62 |
+
"criterion": nn.CrossEntropyLoss(),
|
| 63 |
+
"slices": 3,
|
| 64 |
+
"checkpoint_activation": True,
|
| 65 |
+
"num_microbatches": 1,
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class FSDP:
|
| 70 |
+
def get_model_config():
|
| 71 |
+
return {
|
| 72 |
+
"vocab_size": 10000,
|
| 73 |
+
"ninp": 2048, # embedding dimension
|
| 74 |
+
"nhid": 2048, # the dimension of the feedforward network model in nn.TransformerEncoder
|
| 75 |
+
"nhead": 32, # the number of heads in the multiheadattention models
|
| 76 |
+
"dropout": 0,
|
| 77 |
+
"initrange": 0.1,
|
| 78 |
+
"scaler": GradScaler(),
|
| 79 |
+
"clip_value": 0.05,
|
| 80 |
+
"num_decoder_layers": 10,
|
| 81 |
+
"seq_len": 32,
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
def get_benchmark_config():
|
| 85 |
+
|
| 86 |
+
return {
|
| 87 |
+
"epochs": 1,
|
| 88 |
+
"lr": 0.001, # learning rate
|
| 89 |
+
"batch_size": 8,
|
| 90 |
+
"criterion": nn.CrossEntropyLoss(),
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
def get_golden_real_stats():
|
| 94 |
+
raise NotImplementedError("Synthetic data benchmarks are not supported.")
|
| 95 |
+
|
| 96 |
+
def get_golden_synthetic_stats():
|
| 97 |
+
return {
|
| 98 |
+
"avg_wps": 486.303,
|
| 99 |
+
"std_dev_wps": 71.307,
|
| 100 |
+
"peak_mem_usage": [5.5055 * 2**30, 5.5055 * 2**30, 5.5055 * 2**30, 5.5055 * 2**30],
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class Pipe:
|
| 105 |
+
def get_model_config():
|
| 106 |
+
return {
|
| 107 |
+
"vocab_size": 10000,
|
| 108 |
+
"ninp": 2048, # embedding dimension
|
| 109 |
+
"nhid": 2048, # the dimension of the feedforward network model in nn.TransformerEncoder
|
| 110 |
+
"nhead": 32, # the number of heads in the multiheadattention models
|
| 111 |
+
"dropout": 0,
|
| 112 |
+
"initrange": 0.1,
|
| 113 |
+
"scaler": GradScaler(),
|
| 114 |
+
"clip_value": 0.05,
|
| 115 |
+
"num_decoder_layers": 10,
|
| 116 |
+
"seq_len": 32,
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
def get_benchmark_config():
|
| 120 |
+
|
| 121 |
+
return {
|
| 122 |
+
"epochs": 1,
|
| 123 |
+
"lr": 0.001, # learning rate
|
| 124 |
+
"batch_size": 8,
|
| 125 |
+
"criterion": nn.CrossEntropyLoss(),
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
def get_golden_real_stats():
|
| 129 |
+
return {
|
| 130 |
+
"avg_wps": 703.778,
|
| 131 |
+
"std_dev_wps": 5.732,
|
| 132 |
+
"peak_mem_usage": [2320996352, 1396742144, 1396742144, 2340010496],
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
def get_golden_synthetic_stats():
|
| 136 |
+
# TODO(anj-s): Add support for synthetic regression benchmarks
|
| 137 |
+
raise NotImplementedError("Synthetic data benchmarks are not supported.")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class MOE:
|
| 141 |
+
def get_model_config():
|
| 142 |
+
return {
|
| 143 |
+
"vocab_size": 10000,
|
| 144 |
+
"ninp": 1024, # embedding dimension
|
| 145 |
+
"nhid": 4096, # the dimension of the feedforward network model in nn.TransformerEncoder
|
| 146 |
+
"nhead": 32, # the number of heads in the multiheadattention models
|
| 147 |
+
"dropout": 0,
|
| 148 |
+
"initrange": 0.1,
|
| 149 |
+
"scaler": GradScaler(),
|
| 150 |
+
"clip_value": 0.05,
|
| 151 |
+
"num_decoder_layers": 20,
|
| 152 |
+
"seq_len": 33, # (seq_len - 1) needs to be divisible by num_local_experts
|
| 153 |
+
"is_moe": True,
|
| 154 |
+
"num_local_experts": 2,
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
def get_benchmark_config():
|
| 158 |
+
return {
|
| 159 |
+
"epochs": 1,
|
| 160 |
+
"lr": 0.001, # learning rate
|
| 161 |
+
"batch_size": 32,
|
| 162 |
+
"criterion": nn.CrossEntropyLoss(),
|
| 163 |
+
}
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/golden_configs/oss_mnist.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def get_golden_real_stats():
|
| 8 |
+
|
| 9 |
+
return {
|
| 10 |
+
"reference_speed": 578,
|
| 11 |
+
"reference_memory": 945,
|
| 12 |
+
"reference_loss": 0.026,
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_golden_synthetic_stats():
|
| 17 |
+
# TODO(anj-s): Add support for synthetic regression benchmarks
|
| 18 |
+
raise NotImplementedError("Synthetic data benchmarks are not supported.")
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/models/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/models/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (259 Bytes). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/models/__pycache__/transformer_lm.cpython-311.pyc
ADDED
|
Binary file (14.6 kB). View file
|
|
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/moe.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
import math
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
from golden_configs.lm_wikitext2 import MOE as MOEConfig
|
| 11 |
+
import torch
|
| 12 |
+
import torch.distributed as dist
|
| 13 |
+
import torch.multiprocessing as mp
|
| 14 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 15 |
+
import utils
|
| 16 |
+
|
| 17 |
+
MPI_PORT = 29500
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def benchmark_single_process(config_class, args):
|
| 21 |
+
"""Benchmark a given model using a single process and multiple devices."""
|
| 22 |
+
|
| 23 |
+
world_size = torch.cuda.device_count() if torch.cuda.is_available() else 1
|
| 24 |
+
assert world_size > 0
|
| 25 |
+
benchmark_config = utils.create_benchmark_config(args.model_name, config_class)
|
| 26 |
+
model_specs = utils.get_model_specs(args.model_name, config_class)
|
| 27 |
+
|
| 28 |
+
mp.spawn(train, args=(world_size, benchmark_config, model_specs, args), nprocs=world_size, join=True)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def train(rank, world_size, benchmark_config, model_specs, args):
|
| 32 |
+
logger = mp.log_to_stderr()
|
| 33 |
+
logger.setLevel(logging.DEBUG if args.debug else logging.INFO)
|
| 34 |
+
utils.init_random_seed(rank)
|
| 35 |
+
|
| 36 |
+
init_method_pgroup = "tcp://localhost:{}".format(MPI_PORT)
|
| 37 |
+
torch.distributed.init_process_group(
|
| 38 |
+
backend="nccl", rank=rank, world_size=world_size, init_method=init_method_pgroup
|
| 39 |
+
)
|
| 40 |
+
logger.info("train, rank={}".format(rank))
|
| 41 |
+
device = torch.device("cuda", rank) if torch.cuda.is_available() else torch.device("cpu")
|
| 42 |
+
|
| 43 |
+
criterion = benchmark_config["criterion"]
|
| 44 |
+
|
| 45 |
+
model_config = utils.create_model_config(
|
| 46 |
+
args, benchmark_config=benchmark_config, model_specs=model_specs, device=device
|
| 47 |
+
)
|
| 48 |
+
# vocab_size may change in create_model_config() due to input data
|
| 49 |
+
vocab_size = model_specs["vocab_size"]
|
| 50 |
+
model = model_config["model"]
|
| 51 |
+
model.train()
|
| 52 |
+
optimizer = model_config["optimizer"]
|
| 53 |
+
optimizer = optimizer(model.parameters())
|
| 54 |
+
group = model.group if hasattr(model, "group") else None
|
| 55 |
+
utils.log_number_of_parameters(model, logger)
|
| 56 |
+
|
| 57 |
+
total_loss = 0.0
|
| 58 |
+
word_counter = 0
|
| 59 |
+
total_tokens = 0
|
| 60 |
+
total_tokens_per_log_interval = 0
|
| 61 |
+
bptt = 2
|
| 62 |
+
|
| 63 |
+
total_elapsed = 0.0
|
| 64 |
+
|
| 65 |
+
model = DDP(model, device_ids=[rank], output_device=rank, broadcast_buffers=False)
|
| 66 |
+
lm_dataloader, _, _ = utils.get_data_loader(
|
| 67 |
+
model_config["dataset_info"], args, benchmark_config, model_specs, num_replicas=world_size, rank=rank
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def get_batch(source):
|
| 71 |
+
seq_len = len(source) - 1
|
| 72 |
+
data = source[0:seq_len]
|
| 73 |
+
target = source[1 : 1 + seq_len]
|
| 74 |
+
return data, target
|
| 75 |
+
|
| 76 |
+
for i, batch in enumerate(lm_dataloader):
|
| 77 |
+
if i == 1:
|
| 78 |
+
epoch_start_time = time.time()
|
| 79 |
+
|
| 80 |
+
if args.max_batch and i > args.max_batch:
|
| 81 |
+
break
|
| 82 |
+
|
| 83 |
+
if i > 0:
|
| 84 |
+
total_tokens += batch.numel()
|
| 85 |
+
|
| 86 |
+
start_time = time.time()
|
| 87 |
+
optimizer.zero_grad()
|
| 88 |
+
source, target = get_batch(batch)
|
| 89 |
+
source = source.to(device)
|
| 90 |
+
target = target.to(device)
|
| 91 |
+
try:
|
| 92 |
+
output = model(source.to(device))
|
| 93 |
+
loss = criterion(output.view(-1, vocab_size), target.view(-1))
|
| 94 |
+
total_loss += loss.item()
|
| 95 |
+
loss.backward()
|
| 96 |
+
torch.nn.utils.clip_grad_value_(model.parameters(), model_specs["clip_value"])
|
| 97 |
+
optimizer.step()
|
| 98 |
+
except Exception as e:
|
| 99 |
+
raise RuntimeError(f"training failed on {torch.distributed.get_rank()}") from e
|
| 100 |
+
|
| 101 |
+
elapsed = time.time() - start_time
|
| 102 |
+
total_elapsed += elapsed
|
| 103 |
+
log_interval = 1
|
| 104 |
+
total_tokens_per_log_interval += batch.numel()
|
| 105 |
+
if i % log_interval == 0 and i > 0:
|
| 106 |
+
cur_loss = total_loss / log_interval
|
| 107 |
+
logger.debug(
|
| 108 |
+
"| batch {:5d} | wps {:5.2f} | loss {:5.2f} | ppl {:8.2f}".format(
|
| 109 |
+
i, total_tokens_per_log_interval / elapsed, cur_loss, math.exp(cur_loss)
|
| 110 |
+
)
|
| 111 |
+
)
|
| 112 |
+
total_tokens_per_log_interval = 0
|
| 113 |
+
total_loss = 0
|
| 114 |
+
|
| 115 |
+
wps = total_tokens / total_elapsed
|
| 116 |
+
|
| 117 |
+
logger.debug("rank {}, wps: {}".format(rank, wps))
|
| 118 |
+
logger.debug(
|
| 119 |
+
"Peak allocated bytes on cuda:{}: {:1d}".format(
|
| 120 |
+
dist.get_rank(), torch.cuda.memory_stats(dist.get_rank())["allocated_bytes.all.peak"]
|
| 121 |
+
)
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
args = utils.init_args()
|
| 127 |
+
logging.basicConfig(level=logging.INFO if not args.debug else logging.DEBUG)
|
| 128 |
+
|
| 129 |
+
logging.info(f"Running single process benchmark with args: {args}")
|
| 130 |
+
benchmark_single_process(MOEConfig, args)
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/oss.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
from enum import Enum
|
| 8 |
+
import importlib
|
| 9 |
+
import logging
|
| 10 |
+
import tempfile
|
| 11 |
+
import time
|
| 12 |
+
from typing import Any, List, Optional, cast
|
| 13 |
+
|
| 14 |
+
from golden_configs import oss_mnist
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
import torch.autograd.profiler as profiler
|
| 18 |
+
from torch.cuda.amp import GradScaler as TorchGradScaler
|
| 19 |
+
import torch.distributed as dist
|
| 20 |
+
import torch.multiprocessing as mp
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 23 |
+
from torch.utils.data import BatchSampler, DataLoader, Sampler
|
| 24 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 25 |
+
from torchvision.datasets import MNIST
|
| 26 |
+
from torchvision.transforms import Compose, Resize, ToTensor
|
| 27 |
+
|
| 28 |
+
from benchmarks.datasets.mnist import setup_cached_mnist
|
| 29 |
+
from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP
|
| 30 |
+
from fairscale.optim import OSS
|
| 31 |
+
from fairscale.optim.grad_scaler import ShardedGradScaler
|
| 32 |
+
|
| 33 |
+
TEMPDIR = tempfile.gettempdir()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def dist_init(rank, world_size, backend):
|
| 37 |
+
logging.info(f"Using backend: {backend}")
|
| 38 |
+
dist.init_process_group(backend=backend, init_method="tcp://localhost:29501", rank=rank, world_size=world_size)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def get_problem(rank, world_size, batch_size, device, model_name: str):
|
| 42 |
+
# Select the desired model on the fly
|
| 43 |
+
logging.info(f"Using {model_name} for benchmarking")
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
model = getattr(importlib.import_module("torchvision.models"), model_name)(pretrained=False).to(device)
|
| 47 |
+
except AttributeError:
|
| 48 |
+
model = getattr(importlib.import_module("timm.models"), model_name)(pretrained=False).to(device)
|
| 49 |
+
|
| 50 |
+
# Data setup, duplicate the grey channels to get pseudo color
|
| 51 |
+
def collate(inputs: List[Any]):
|
| 52 |
+
return {
|
| 53 |
+
"inputs": torch.stack([i[0] for i in inputs]).repeat(1, 3, 1, 1).to(device),
|
| 54 |
+
"label": torch.tensor([i[1] for i in inputs]).to(device),
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
# Transforms
|
| 58 |
+
transforms = []
|
| 59 |
+
if model_name.startswith("vit"):
|
| 60 |
+
# ViT models are fixed size. Add a ad-hoc transform to resize the pictures accordingly
|
| 61 |
+
pic_size = int(model_name.split("_")[-1])
|
| 62 |
+
transforms.append(Resize(pic_size))
|
| 63 |
+
|
| 64 |
+
transforms.append(ToTensor())
|
| 65 |
+
|
| 66 |
+
dataset = MNIST(transform=Compose(transforms), download=False, root=TEMPDIR)
|
| 67 |
+
sampler: Sampler = DistributedSampler(dataset, num_replicas=world_size, rank=rank)
|
| 68 |
+
batch_sampler = BatchSampler(sampler, batch_size, drop_last=True)
|
| 69 |
+
dataloader = DataLoader(dataset=dataset, batch_sampler=batch_sampler, collate_fn=collate)
|
| 70 |
+
|
| 71 |
+
loss_fn = nn.CrossEntropyLoss()
|
| 72 |
+
return model, dataloader, loss_fn
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class OptimType(str, Enum):
|
| 76 |
+
vanilla = "pytorch"
|
| 77 |
+
oss_ddp = "oss_ddp"
|
| 78 |
+
oss_sharded_ddp = "oss_sharded_ddp"
|
| 79 |
+
everyone = "everyone"
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def validate_benchmark(measurements, final_loss, args, check_regression):
|
| 83 |
+
"""Validate the measurments against the golden benchmark config."""
|
| 84 |
+
|
| 85 |
+
golden_data = oss_mnist.get_golden_real_stats()
|
| 86 |
+
|
| 87 |
+
max_memory = -1.0
|
| 88 |
+
rank = dist.get_rank()
|
| 89 |
+
if not args.cpu:
|
| 90 |
+
# TODO(anj-s): Check if we need to synchronize before we caculate total training time.
|
| 91 |
+
torch.cuda.synchronize(rank)
|
| 92 |
+
max_memory = torch.cuda.max_memory_allocated(rank) / 2**20
|
| 93 |
+
logging.info(f"[{rank}] : Peak memory {max_memory:.1f}MiB")
|
| 94 |
+
|
| 95 |
+
measurements.sort()
|
| 96 |
+
median = measurements[len(measurements) // 2]
|
| 97 |
+
# Compute the median and median of absolute differences img per second.
|
| 98 |
+
abs_diff = list(map(lambda x: abs(x - median), measurements))
|
| 99 |
+
abs_diff.sort()
|
| 100 |
+
mad = abs_diff[len(measurements) // 2] if args.epochs > 2 else -1
|
| 101 |
+
|
| 102 |
+
# TODO(anj-s): Add a debug flag to perform the above calculation only when required.
|
| 103 |
+
logging.info(f"[{rank}] : Median speed: {median:.2f} +/- {mad:.2f}")
|
| 104 |
+
|
| 105 |
+
if check_regression and rank == 0:
|
| 106 |
+
assert median + 8.0 * mad > golden_data["reference_speed"], (
|
| 107 |
+
f"Speed regression detected: " f"{median + 8.0 * mad} vs. {golden_data['reference_speed']}"
|
| 108 |
+
)
|
| 109 |
+
assert max_memory < 1.05 * golden_data["reference_memory"], (
|
| 110 |
+
f"Memory use regression detected: " f"{max_memory} vs. {1.05* golden_data['reference_memory']}"
|
| 111 |
+
)
|
| 112 |
+
# any min_loss < than golden + epsilon is OK.
|
| 113 |
+
assert cast(float, final_loss) - golden_data["reference_loss"] < 1e-2, (
|
| 114 |
+
f"Loss regression detected: " f"{final_loss} vs. {golden_data['reference_loss']}"
|
| 115 |
+
)
|
| 116 |
+
logging.info("[Regression Test] VALID")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def train(
|
| 120 |
+
rank: int,
|
| 121 |
+
args: argparse.Namespace,
|
| 122 |
+
backend: str = "gloo",
|
| 123 |
+
optim_type: OptimType = OptimType.vanilla,
|
| 124 |
+
check_regression: bool = True,
|
| 125 |
+
):
|
| 126 |
+
logging.basicConfig(level=logging.INFO if not args.debug else logging.DEBUG)
|
| 127 |
+
|
| 128 |
+
use_multi_tensor = args.multi_tensor_optim and hasattr(torch.optim, "_multi_tensor")
|
| 129 |
+
OPTIM = torch.optim._multi_tensor.RMSprop if use_multi_tensor else torch.optim.RMSprop # type: ignore # attr is checked but mypy misses that
|
| 130 |
+
logging.info("Multi tensor optimizer: {}".format(use_multi_tensor))
|
| 131 |
+
|
| 132 |
+
# DDP
|
| 133 |
+
dist_init(rank=rank, world_size=args.world_size, backend=backend)
|
| 134 |
+
|
| 135 |
+
# Setup
|
| 136 |
+
if not args.cpu:
|
| 137 |
+
torch.cuda.set_device(rank)
|
| 138 |
+
torch.cuda.manual_seed(0)
|
| 139 |
+
torch.manual_seed(0) # also sets the cuda seed
|
| 140 |
+
np.random.seed(0)
|
| 141 |
+
|
| 142 |
+
if backend == "nccl":
|
| 143 |
+
torch.backends.cudnn.deterministic = True
|
| 144 |
+
torch.backends.cudnn.benchmark = False
|
| 145 |
+
|
| 146 |
+
device = torch.device("cpu") if args.cpu else torch.device(rank)
|
| 147 |
+
model, dataloader, loss_fn = get_problem(rank, args.world_size, args.batch_size, device, args.model)
|
| 148 |
+
|
| 149 |
+
# Shard the optimizer
|
| 150 |
+
optimizer: Optional[torch.optim.Optimizer] = None
|
| 151 |
+
model = cast(nn.Module, model)
|
| 152 |
+
scaler = (TorchGradScaler() if args.optim_type == OptimType.vanilla else ShardedGradScaler()) if args.amp else None
|
| 153 |
+
|
| 154 |
+
if optim_type == OptimType.oss_sharded_ddp:
|
| 155 |
+
optimizer = OSS(params=model.parameters(), optim=OPTIM, lr=1e-4, momentum=0.9)
|
| 156 |
+
# Single node run typically, no need for reduce buckets
|
| 157 |
+
model = ShardedDDP(model, optimizer, reduce_buffer_size=0)
|
| 158 |
+
else:
|
| 159 |
+
device_ids = None if args.cpu else [rank]
|
| 160 |
+
model = DDP(model, device_ids=device_ids, find_unused_parameters=False) # type: ignore
|
| 161 |
+
optimizer = (
|
| 162 |
+
OSS(params=model.parameters(), optim=OPTIM, lr=1e-4, momentum=0.9)
|
| 163 |
+
if optim_type == OptimType.oss_ddp
|
| 164 |
+
else OPTIM(model.parameters(), lr=1e-4, momentum=0.9)
|
| 165 |
+
)
|
| 166 |
+
optimizer = cast(torch.optim.Optimizer, optimizer)
|
| 167 |
+
|
| 168 |
+
# Reset the memory use counter
|
| 169 |
+
if not args.cpu:
|
| 170 |
+
torch.cuda.empty_cache()
|
| 171 |
+
torch.cuda.reset_peak_memory_stats(rank)
|
| 172 |
+
torch.cuda.synchronize(rank)
|
| 173 |
+
|
| 174 |
+
# Standard training loop
|
| 175 |
+
training_start = time.monotonic()
|
| 176 |
+
model.train()
|
| 177 |
+
|
| 178 |
+
measurements = []
|
| 179 |
+
final_loss: Optional[float] = -1.0
|
| 180 |
+
min_loss = 100.0
|
| 181 |
+
need_profiling = args.profile
|
| 182 |
+
|
| 183 |
+
for epoch in range(args.epochs):
|
| 184 |
+
n_items = 0
|
| 185 |
+
epoch_runtime = 0.0
|
| 186 |
+
|
| 187 |
+
for batch in dataloader:
|
| 188 |
+
if not args.cpu:
|
| 189 |
+
torch.cuda.synchronize(rank)
|
| 190 |
+
batch_start = time.monotonic()
|
| 191 |
+
|
| 192 |
+
def closure(data=batch, grad_scaler=None):
|
| 193 |
+
model.zero_grad()
|
| 194 |
+
if args.debug and rank == 0 and next(model.parameters()).grad is not None:
|
| 195 |
+
logging.debug(
|
| 196 |
+
"\nbefore: param {} -- grad {}".format(
|
| 197 |
+
next(model.parameters()).norm().item(), next(model.parameters()).grad.norm().item()
|
| 198 |
+
)
|
| 199 |
+
)
|
| 200 |
+
if grad_scaler is not None:
|
| 201 |
+
# Automatically computes the FW pass in half precision
|
| 202 |
+
with torch.cuda.amp.autocast():
|
| 203 |
+
outputs = model(data["inputs"])
|
| 204 |
+
loss = loss_fn(outputs, data["label"])
|
| 205 |
+
|
| 206 |
+
# Accumulates scaled gradients.
|
| 207 |
+
grad_scaler.scale(loss).backward()
|
| 208 |
+
else:
|
| 209 |
+
outputs = model(data["inputs"])
|
| 210 |
+
loss = loss_fn(outputs, data["label"])
|
| 211 |
+
loss.backward()
|
| 212 |
+
|
| 213 |
+
if args.debug and rank == 0 and next(model.parameters()).grad is not None:
|
| 214 |
+
logging.debug(
|
| 215 |
+
"after BW: param {} -- grad {}".format(
|
| 216 |
+
next(model.parameters()).norm().item(), next(model.parameters()).grad.norm().item()
|
| 217 |
+
)
|
| 218 |
+
)
|
| 219 |
+
return loss
|
| 220 |
+
|
| 221 |
+
def run_closure(closure, scaler, optimizer):
|
| 222 |
+
if scaler is not None:
|
| 223 |
+
final_loss = closure(grad_scaler=scaler) # AMP scaler.step does not support closures
|
| 224 |
+
scaler.step(optimizer)
|
| 225 |
+
scaler.update()
|
| 226 |
+
return final_loss
|
| 227 |
+
else:
|
| 228 |
+
return optimizer.step(closure)
|
| 229 |
+
|
| 230 |
+
if need_profiling and not args.cpu:
|
| 231 |
+
logging.info("Profiling the run")
|
| 232 |
+
with profiler.profile(use_cuda=True, record_shapes=True, profile_memory=True) as prof: # type: ignore
|
| 233 |
+
with profiler.record_function("batch"):
|
| 234 |
+
final_loss = run_closure(closure, scaler, optimizer)
|
| 235 |
+
|
| 236 |
+
prof.export_chrome_trace(f"{optim_type}_trace_rank_{rank}.json")
|
| 237 |
+
need_profiling = False # only profile once
|
| 238 |
+
|
| 239 |
+
else:
|
| 240 |
+
final_loss = run_closure(closure, scaler, optimizer)
|
| 241 |
+
|
| 242 |
+
if args.debug and rank == 0:
|
| 243 |
+
logging.debug("buffer: {}".format(next(model.buffers()).norm().item()))
|
| 244 |
+
logging.debug(
|
| 245 |
+
"after update: param {} -- grad {}".format(
|
| 246 |
+
next(model.parameters()).norm().item(), next(model.parameters()).grad.norm().item()
|
| 247 |
+
)
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
n_items += args.batch_size
|
| 251 |
+
|
| 252 |
+
if not args.cpu:
|
| 253 |
+
# make sure that the cuda kernels are finished before taking a timestamp
|
| 254 |
+
torch.cuda.synchronize(rank)
|
| 255 |
+
|
| 256 |
+
batch_end = time.monotonic()
|
| 257 |
+
epoch_runtime += batch_end - batch_start
|
| 258 |
+
|
| 259 |
+
if optim_type == OptimType.oss_ddp or optim_type == OptimType.oss_sharded_ddp:
|
| 260 |
+
# Check the checkpointing in the case of the OSS optimizer
|
| 261 |
+
# Memory usage could spill over from there
|
| 262 |
+
optimizer = cast(OSS, optimizer)
|
| 263 |
+
optimizer.consolidate_state_dict()
|
| 264 |
+
if dist.get_rank() == 0:
|
| 265 |
+
_ = optimizer.state_dict()
|
| 266 |
+
logging.info("... State dict collected")
|
| 267 |
+
|
| 268 |
+
measurements.append(n_items / epoch_runtime)
|
| 269 |
+
min_loss = min(min_loss, final_loss)
|
| 270 |
+
if dist.get_rank() == 0:
|
| 271 |
+
logging.info(
|
| 272 |
+
f"Epoch {epoch} - processed {measurements[-1]:.2f} img per sec. "
|
| 273 |
+
f"Loss {final_loss:.3f} min loss {min_loss:.3f}"
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
training_stop = time.monotonic()
|
| 277 |
+
img_per_sec = n_items / (training_stop - training_start) * args.epochs
|
| 278 |
+
logging.info(f"[{dist.get_rank()}] : Training done. {img_per_sec:.2f} img per sec inc. checkpoint")
|
| 279 |
+
|
| 280 |
+
# Use min_loss to check instead of final_loss since the final_loss is a bit random.
|
| 281 |
+
# If the training min_loss reaches certain number, we can be reasonably certain the
|
| 282 |
+
# training process was correct.
|
| 283 |
+
validate_benchmark(measurements, min_loss, args, check_regression)
|
| 284 |
+
|
| 285 |
+
dist.destroy_process_group() # type: ignore
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
if __name__ == "__main__":
|
| 289 |
+
parser = argparse.ArgumentParser(
|
| 290 |
+
description="Benchmark the optimizer state sharding, on a typical computer vision workload"
|
| 291 |
+
)
|
| 292 |
+
parser.add_argument("--world_size", action="store", default=2, type=int)
|
| 293 |
+
parser.add_argument("--epochs", action="store", default=10, type=int)
|
| 294 |
+
parser.add_argument("--batch_size", action="store", default=256, type=int)
|
| 295 |
+
parser.add_argument("--check_regression", action="store_true", default=False)
|
| 296 |
+
parser.add_argument(
|
| 297 |
+
"--optim_type", type=OptimType, choices=[o.value for o in OptimType], default=OptimType.everyone
|
| 298 |
+
)
|
| 299 |
+
parser.add_argument("--gloo", action="store_true", default=False)
|
| 300 |
+
parser.add_argument("--profile", action="store_true", default=False)
|
| 301 |
+
parser.add_argument("--cpu", action="store_true", default=False)
|
| 302 |
+
parser.add_argument("--model", type=str, help="Any torchvision or timm model name (str)", default="resnet101")
|
| 303 |
+
parser.add_argument("--debug", action="store_true", default=False, help="Display additional debug information")
|
| 304 |
+
parser.add_argument("--amp", action="store_true", default=False, help="Activate torch AMP")
|
| 305 |
+
parser.add_argument(
|
| 306 |
+
"--multi_tensor_optim", action="store_true", default=False, help="Use the faster multi-tensor optimizers"
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
args = parser.parse_args()
|
| 310 |
+
|
| 311 |
+
logging.basicConfig(level=logging.INFO if not args.debug else logging.DEBUG)
|
| 312 |
+
logging.info("Benchmark arguments: %s" % args)
|
| 313 |
+
|
| 314 |
+
BACKEND = "nccl" if (not args.gloo or not torch.cuda.is_available()) and not args.cpu else "gloo"
|
| 315 |
+
|
| 316 |
+
# Download dataset once for all processes
|
| 317 |
+
setup_cached_mnist()
|
| 318 |
+
|
| 319 |
+
# Benchmark the different configurations, via multiple processes
|
| 320 |
+
if args.optim_type == OptimType.vanilla or args.optim_type == OptimType.everyone:
|
| 321 |
+
logging.info("\n*** Benchmark vanilla optimizer")
|
| 322 |
+
mp.spawn(
|
| 323 |
+
train, # type: ignore
|
| 324 |
+
args=(args, BACKEND, OptimType.vanilla, False), # no regression check
|
| 325 |
+
nprocs=args.world_size,
|
| 326 |
+
join=True,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
if args.optim_type == OptimType.oss_ddp or args.optim_type == OptimType.everyone:
|
| 330 |
+
logging.info("\n*** Benchmark OSS with DDP")
|
| 331 |
+
mp.spawn(
|
| 332 |
+
train,
|
| 333 |
+
args=(args, BACKEND, OptimType.oss_ddp, args.check_regression),
|
| 334 |
+
nprocs=args.world_size,
|
| 335 |
+
join=True, # type: ignore
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
if args.optim_type == OptimType.oss_sharded_ddp or args.optim_type == OptimType.everyone:
|
| 339 |
+
logging.info("\n*** Benchmark OSS with ShardedDDP")
|
| 340 |
+
mp.spawn(
|
| 341 |
+
train, # type: ignore
|
| 342 |
+
args=(
|
| 343 |
+
args,
|
| 344 |
+
BACKEND,
|
| 345 |
+
OptimType.oss_sharded_ddp,
|
| 346 |
+
args.check_regression,
|
| 347 |
+
),
|
| 348 |
+
nprocs=args.world_size,
|
| 349 |
+
join=True,
|
| 350 |
+
)
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/pipe.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
import gc
|
| 8 |
+
import logging
|
| 9 |
+
import math
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.distributed as dist
|
| 14 |
+
from torch.distributed import rpc
|
| 15 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 16 |
+
import utils
|
| 17 |
+
|
| 18 |
+
from benchmarks.golden_configs.lm_wikitext2 import Pipe as lm_wikitext2
|
| 19 |
+
from fairscale.fair_dev.testing.testing import dist_init
|
| 20 |
+
from fairscale.nn import Pipe
|
| 21 |
+
from fairscale.nn.model_parallel import initialize_model_parallel
|
| 22 |
+
|
| 23 |
+
MPI_PORT = 29500
|
| 24 |
+
RPC_PORT = 29501
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_tensors_by_size_bucket():
|
| 28 |
+
|
| 29 |
+
size_buckets = defaultdict(int)
|
| 30 |
+
for obj in gc.get_objects():
|
| 31 |
+
if not isinstance(obj, torch.Tensor):
|
| 32 |
+
continue
|
| 33 |
+
if obj.device.type == "cuda":
|
| 34 |
+
size_buckets[(*obj.size(),) + (obj.element_size(),)] += 1
|
| 35 |
+
|
| 36 |
+
return size_buckets
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def get_device(model, index):
|
| 40 |
+
if isinstance(model, DDP):
|
| 41 |
+
model = model.module
|
| 42 |
+
|
| 43 |
+
if not torch.cuda.is_available():
|
| 44 |
+
return torch.device("cpu")
|
| 45 |
+
if hasattr(model, "devices"):
|
| 46 |
+
return model.devices[index]
|
| 47 |
+
else:
|
| 48 |
+
return torch.cuda.current_device()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_fake_dataloader(lm_dataloader_len, args):
|
| 52 |
+
fake_input = {"input": torch.zeros(args.batch_size)}
|
| 53 |
+
|
| 54 |
+
class FakeDataset:
|
| 55 |
+
def __getitem__(self, index):
|
| 56 |
+
return fake_input
|
| 57 |
+
|
| 58 |
+
def __len__(self):
|
| 59 |
+
return lm_dataloader_len
|
| 60 |
+
|
| 61 |
+
return FakeDataset()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def train(model_config, model, benchmark_config, model_specs, args):
|
| 65 |
+
lm_dataloader, _, _ = utils.get_data_loader(model_config["dataset_info"], args, benchmark_config, model_specs)
|
| 66 |
+
criterion = benchmark_config["criterion"]
|
| 67 |
+
vocab_size = model_specs["vocab_size"]
|
| 68 |
+
optimizer = model_config["optimizer"]
|
| 69 |
+
|
| 70 |
+
model.train()
|
| 71 |
+
utils.log_number_of_parameters(model)
|
| 72 |
+
|
| 73 |
+
total_loss = 0.0
|
| 74 |
+
word_counter = 0
|
| 75 |
+
|
| 76 |
+
optimizer = optimizer(model.parameters())
|
| 77 |
+
|
| 78 |
+
pipe_group = model.group if hasattr(model, "group") else None
|
| 79 |
+
|
| 80 |
+
# TODO(anj-s): Avoid sending fake data to all replicas except the first and last one.
|
| 81 |
+
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
| 82 |
+
if pipe_group and pipe_group.rank() != 0 and pipe_group.rank() != (pipe_group.size() - 1):
|
| 83 |
+
lm_dataloader, _, _ = get_synthetic_dataloaders(args, benchmark_config, model_specs)
|
| 84 |
+
|
| 85 |
+
total_tokens = 0
|
| 86 |
+
total_tokens_per_log_interval = 0
|
| 87 |
+
bptt = 2
|
| 88 |
+
start_time = time.time()
|
| 89 |
+
epoch_start_time = 0.0
|
| 90 |
+
|
| 91 |
+
def get_batch(source):
|
| 92 |
+
seq_len = len(source) - 1
|
| 93 |
+
data = source[0:seq_len]
|
| 94 |
+
target = source[1 : 1 + seq_len]
|
| 95 |
+
return data, target
|
| 96 |
+
|
| 97 |
+
for i, batch in enumerate(lm_dataloader):
|
| 98 |
+
if i == 1:
|
| 99 |
+
epoch_start_time = time.time()
|
| 100 |
+
|
| 101 |
+
source, target = get_batch(batch)
|
| 102 |
+
if args.max_batch and i > args.max_batch:
|
| 103 |
+
break
|
| 104 |
+
|
| 105 |
+
if i > 0:
|
| 106 |
+
total_tokens += source.numel()
|
| 107 |
+
|
| 108 |
+
optimizer.zero_grad()
|
| 109 |
+
try:
|
| 110 |
+
if pipe_group is None or pipe_group.rank() == 0:
|
| 111 |
+
tmp = source.to(get_device(model, 0))
|
| 112 |
+
output = model(tmp)
|
| 113 |
+
else:
|
| 114 |
+
output = model(source)
|
| 115 |
+
except Exception as e:
|
| 116 |
+
raise RuntimeError(f"training failed on {torch.distributed.get_rank()}") from e
|
| 117 |
+
|
| 118 |
+
if pipe_group is None or pipe_group.rank() == pipe_group.size() - 1:
|
| 119 |
+
target = target.to(get_device(model, -1))
|
| 120 |
+
output = output.to(target.device)
|
| 121 |
+
loss = criterion(output.view(-1, vocab_size), target.view(-1))
|
| 122 |
+
loss.backward()
|
| 123 |
+
del target
|
| 124 |
+
else:
|
| 125 |
+
model.back_helper(output)
|
| 126 |
+
|
| 127 |
+
del output
|
| 128 |
+
|
| 129 |
+
torch.nn.utils.clip_grad_value_(model.parameters(), model_specs["clip_value"])
|
| 130 |
+
optimizer.step()
|
| 131 |
+
|
| 132 |
+
if pipe_group is None or pipe_group.rank() == pipe_group.size() - 1:
|
| 133 |
+
total_loss += loss.item()
|
| 134 |
+
log_interval = 1
|
| 135 |
+
total_tokens_per_log_interval += source.numel()
|
| 136 |
+
if i % log_interval == 0 and i > 0:
|
| 137 |
+
cur_loss = total_loss / log_interval
|
| 138 |
+
elapsed = time.time() - start_time
|
| 139 |
+
if dist.get_rank() == dist.get_world_size() - 1:
|
| 140 |
+
logging.debug(
|
| 141 |
+
"| batch {:5d} | wps {:5.2f} | loss {:5.2f} | ppl {:8.2f}".format(
|
| 142 |
+
i, total_tokens_per_log_interval / elapsed, cur_loss, math.exp(cur_loss)
|
| 143 |
+
)
|
| 144 |
+
)
|
| 145 |
+
total_tokens_per_log_interval = 0
|
| 146 |
+
total_loss = 0
|
| 147 |
+
start_time = time.time()
|
| 148 |
+
|
| 149 |
+
if epoch_start_time != 0:
|
| 150 |
+
wps = total_tokens / (time.time() - epoch_start_time)
|
| 151 |
+
else:
|
| 152 |
+
raise RuntimeError(
|
| 153 |
+
"Unable to benchmark on a single batch. Increase the size " " of the dataset and rerun the benchmark."
|
| 154 |
+
)
|
| 155 |
+
if dist.get_rank() == dist.get_world_size() - 1:
|
| 156 |
+
return wps, loss.item()
|
| 157 |
+
else:
|
| 158 |
+
return 0.0, 0.0
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# TODO(anj-s): Add an option for users to be able to benchmark evaluate.
|
| 162 |
+
def evaluate(eval_model, data_source, criterion, ntokens):
|
| 163 |
+
eval_model.eval()
|
| 164 |
+
total_loss = 0.0
|
| 165 |
+
# TODO(anj-s): Move this to the benchmark config if we want to benchmark evaluation.
|
| 166 |
+
bptt = 35
|
| 167 |
+
|
| 168 |
+
def get_batch(source, i, bptt):
|
| 169 |
+
seq_len = min(bptt, len(source) - 1 - i)
|
| 170 |
+
data = source[i : i + seq_len]
|
| 171 |
+
target = source[i + 1 : i + 1 + seq_len].view(-1)
|
| 172 |
+
return data, target
|
| 173 |
+
|
| 174 |
+
with torch.no_grad():
|
| 175 |
+
for i in range(0, data_source.size(0) - 1, bptt):
|
| 176 |
+
data, targets = get_batch(data_source, i, bptt)
|
| 177 |
+
output = eval_model(data)
|
| 178 |
+
output = output.to(targets.device)
|
| 179 |
+
output_flat = output.view(-1, ntokens)
|
| 180 |
+
total_loss += len(data) * criterion(output_flat, targets).item()
|
| 181 |
+
return total_loss / (len(data_source) - 1)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def get_number_of_words(data):
|
| 185 |
+
return data.size()[0] * data.size()[1]
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def verify_peak_memory(rank, golden_config, std_dev):
|
| 189 |
+
logging.debug(
|
| 190 |
+
"Peak allocated bytes on cuda:0: {:1d}".format(torch.cuda.memory_stats(rank)["allocated_bytes.all.peak"])
|
| 191 |
+
)
|
| 192 |
+
current_device_usage = torch.cuda.memory_stats(rank)["allocated_bytes.all.peak"]
|
| 193 |
+
golden_ref = golden_config["peak_mem_usage"][rank]
|
| 194 |
+
if not current_device_usage < golden_ref * std_dev:
|
| 195 |
+
raise RuntimeError(
|
| 196 |
+
"Peak memory usage for cuda device {:d} is {:d} which"
|
| 197 |
+
"is less than golden reference value of {:d}".format(rank, current_device_usage, golden_ref)
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def verify_lm_run(wps, golden_config, args):
|
| 202 |
+
"""Verify that words per second for a given benchmark run matches the golden data."""
|
| 203 |
+
|
| 204 |
+
if dist.get_rank() == dist.get_world_size() - 1:
|
| 205 |
+
# Assert that words per second is within 3 standard deviations of the average
|
| 206 |
+
# of five golden runs
|
| 207 |
+
logging.info("Throughput(wps) is {:.2f}.".format(wps))
|
| 208 |
+
if not wps > (golden_config["avg_wps"] - (3 * golden_config["std_dev_wps"])):
|
| 209 |
+
raise RuntimeError(
|
| 210 |
+
"Throughput(wps):{:.2f} is below the golden threshold of an "
|
| 211 |
+
"average value of {:.2f} and standard dev of {:.2f}.".format(
|
| 212 |
+
wps, golden_config["avg_wps"], golden_config["std_dev_wps"]
|
| 213 |
+
)
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
for i in range(4):
|
| 217 |
+
verify_peak_memory(i, golden_config, 1.1)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def benchmark_language_model(model_config, model, benchmark_config, model_specs, config_class, args):
|
| 221 |
+
golden_config = get_golden_config(args.model_name, config_class, args)
|
| 222 |
+
epoch = benchmark_config["epochs"]
|
| 223 |
+
start_time = time.time()
|
| 224 |
+
if dist.get_rank() == dist.get_world_size() - 1:
|
| 225 |
+
logging.debug("-" * 110)
|
| 226 |
+
logging.debug("| start of epoch {:1d}".format(epoch))
|
| 227 |
+
logging.debug("-" * 110)
|
| 228 |
+
wps, loss = train(model_config, model, benchmark_config, model_specs, args)
|
| 229 |
+
elapsed_time = time.time() - start_time
|
| 230 |
+
if dist.get_rank() == dist.get_world_size() - 1:
|
| 231 |
+
logging.debug("-" * 110)
|
| 232 |
+
logging.debug("| end of epoch {:1d} | time: {:5.2f}s | train loss {:5.2f} ".format(epoch, elapsed_time, loss))
|
| 233 |
+
logging.debug("-" * 110)
|
| 234 |
+
logging.debug("Throughput(wps) is {:.2f}.".format(wps))
|
| 235 |
+
logging.debug(
|
| 236 |
+
"Peak allocated bytes on cuda:{}: {:1d}".format(
|
| 237 |
+
dist.get_rank(), torch.cuda.memory_stats(dist.get_rank())["allocated_bytes.all.peak"]
|
| 238 |
+
)
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
if len(model.balance) == 4:
|
| 242 |
+
if args.model_name == "lm":
|
| 243 |
+
verify_lm_run(wps, golden_config, args)
|
| 244 |
+
else:
|
| 245 |
+
raise RuntimeError("Unrecognized args.model_name " % args.model_name)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def generate_balance(num_devices, num_layers):
|
| 249 |
+
balance = []
|
| 250 |
+
layers_assigned = 0
|
| 251 |
+
for i in range(num_devices):
|
| 252 |
+
x = (num_layers - layers_assigned) / (num_devices - i)
|
| 253 |
+
if x.is_integer():
|
| 254 |
+
balance.append(int(x))
|
| 255 |
+
layers_assigned += x
|
| 256 |
+
else:
|
| 257 |
+
balance.append(math.ceil(x))
|
| 258 |
+
layers_assigned += math.ceil(x)
|
| 259 |
+
return balance
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def get_golden_config(model_name, config_class, args):
|
| 263 |
+
"""Return a dict with the golden data for throughput and memory usage."""
|
| 264 |
+
|
| 265 |
+
if model_name == "lm":
|
| 266 |
+
return config_class.get_golden_real_stats()
|
| 267 |
+
else:
|
| 268 |
+
raise RuntimeError("Unrecognized args.model_mame " % args.model_name)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def benchmark_single_process(config_class, args):
|
| 272 |
+
"""Benchmark a given model using a single process and multiple devices."""
|
| 273 |
+
|
| 274 |
+
init_method_pgroup = "tcp://localhost:{}".format(MPI_PORT)
|
| 275 |
+
torch.distributed.init_process_group(backend="gloo", rank=0, world_size=1, init_method=init_method_pgroup)
|
| 276 |
+
|
| 277 |
+
num_devices = torch.cuda.device_count() if torch.cuda.is_available() else 1
|
| 278 |
+
assert num_devices > 0
|
| 279 |
+
utils.init_random_seed(0)
|
| 280 |
+
|
| 281 |
+
benchmark_config = utils.create_benchmark_config(args.model_name, config_class)
|
| 282 |
+
model_specs = utils.get_model_specs(args.model_name, config_class)
|
| 283 |
+
model_config = utils.create_model_config(args, benchmark_config=benchmark_config, model_specs=model_specs)
|
| 284 |
+
model = model_config["model"]
|
| 285 |
+
|
| 286 |
+
balance = generate_balance(min(num_devices, 4), len(model))
|
| 287 |
+
pipe_model = Pipe(model, balance, chunks=args.chunks, checkpoint=args.checkpoint)
|
| 288 |
+
del model
|
| 289 |
+
del model_config["model"]
|
| 290 |
+
|
| 291 |
+
if args.dry_run:
|
| 292 |
+
train(model_config, pipe_model, benchmark_config, model_specs, args)
|
| 293 |
+
else:
|
| 294 |
+
benchmark_language_model(model_config, pipe_model, benchmark_config, model_specs, config_class, args)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def run_worker(rank, world_size, args):
|
| 298 |
+
if args.world_size != 0:
|
| 299 |
+
world_size = args.world_size
|
| 300 |
+
dist_init(rank + args.rank_base, world_size, hostname=args.host)
|
| 301 |
+
initialize_model_parallel(1, world_size)
|
| 302 |
+
utils.init_random_seed(0)
|
| 303 |
+
run_mp_worker(args, world_size)
|
| 304 |
+
|
| 305 |
+
rpc.shutdown()
|
| 306 |
+
torch.distributed.destroy_process_group()
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
if __name__ == "__main__":
|
| 310 |
+
args = utils.init_args()
|
| 311 |
+
logging.basicConfig(level=logging.INFO if not args.debug else logging.DEBUG)
|
| 312 |
+
|
| 313 |
+
logging.info(f"Running single process benchmark with args: {args}")
|
| 314 |
+
benchmark_single_process(lm_wikitext2, args)
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/benchmarks/utils.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the BSD license found in the
|
| 4 |
+
# LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
from functools import reduce
|
| 8 |
+
import logging
|
| 9 |
+
import operator
|
| 10 |
+
|
| 11 |
+
import datasets.wikitext2_data as wikitext2_data
|
| 12 |
+
from models import transformer_lm
|
| 13 |
+
import numpy as np
|
| 14 |
+
import torch
|
| 15 |
+
from torch.optim import Adam
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def init_random_seed(seed: int):
|
| 19 |
+
torch.manual_seed(seed)
|
| 20 |
+
torch.cuda.manual_seed(seed)
|
| 21 |
+
np.random.seed(seed)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def init_args():
|
| 25 |
+
parser = argparse.ArgumentParser(description="benchmark")
|
| 26 |
+
parser.add_argument("--host", "-o", type=str, default="localhost", help="hostname")
|
| 27 |
+
parser.add_argument("--chunks", type=int, default=1, help="number of microbatches per batch")
|
| 28 |
+
parser.add_argument("--batch-size", type=int, default=8, help="size of a batch")
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"--checkpoint",
|
| 31 |
+
default="never",
|
| 32 |
+
choices=["always", "except_last", "never"],
|
| 33 |
+
help="Checkpointing strategy for pipe",
|
| 34 |
+
)
|
| 35 |
+
parser.add_argument(
|
| 36 |
+
"--lazy-construction", action="store_true", default=False, help="Number of decoder layers in the model"
|
| 37 |
+
)
|
| 38 |
+
parser.add_argument("--max-batch", type=int, default=4, help="Max number of batches")
|
| 39 |
+
parser.add_argument("--use_synthetic_data", action="store_true", help="Uses synthetic data for running benchmarks.")
|
| 40 |
+
parser.add_argument("--dry_run", action="store_true", help="Run a sample training run without regression testing.")
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
# TODO(anj-s): In the process of adding more models and hence the requirement for a flag.
|
| 43 |
+
"--model_name",
|
| 44 |
+
default="lm",
|
| 45 |
+
help="Language Model(LM) used to benchmark nn.pipe.",
|
| 46 |
+
)
|
| 47 |
+
parser.add_argument("--debug", action="store_true", default=False, help="Display additional debug information")
|
| 48 |
+
args = parser.parse_args()
|
| 49 |
+
return args
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def create_benchmark_config(model_name, config_class):
|
| 53 |
+
"""Return a dict with configurations required for benchmarking `model_name` model."""
|
| 54 |
+
|
| 55 |
+
if model_name == "lm":
|
| 56 |
+
return config_class.get_benchmark_config()
|
| 57 |
+
else:
|
| 58 |
+
raise RuntimeError("Unrecognized args.model_mame " % args.model_name)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def get_model_specs(model_name, config_class):
|
| 62 |
+
"""Return a dict with configurations required for configuring `model_name` model."""
|
| 63 |
+
|
| 64 |
+
if model_name == "lm":
|
| 65 |
+
return config_class.get_model_config()
|
| 66 |
+
else:
|
| 67 |
+
raise RuntimeError("Unrecognized args.model_mame " % model_name)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def create_model_config(args, benchmark_config=None, model_specs=None, device=None):
|
| 71 |
+
"""Return a dict with the given model, dataset and optimizer."""
|
| 72 |
+
|
| 73 |
+
if not device:
|
| 74 |
+
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
| 75 |
+
dataset_info = get_dataset_info(args)
|
| 76 |
+
assert model_specs is not None
|
| 77 |
+
model_specs["vocab_size"] = dataset_info.ntokens
|
| 78 |
+
model, optimizer = get_model_and_optimizer(args, device, benchmark_config, model_specs)
|
| 79 |
+
return {
|
| 80 |
+
"model": model,
|
| 81 |
+
"optimizer": optimizer,
|
| 82 |
+
"dataset_info": dataset_info,
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def get_model_and_optimizer(args, device, benchmark_config, model_config):
|
| 87 |
+
"""Return instantiated model and optimizer function."""
|
| 88 |
+
|
| 89 |
+
if args.model_name == "lm":
|
| 90 |
+
model = get_lm_model(args, device, model_config)
|
| 91 |
+
|
| 92 |
+
lr = benchmark_config["lr"]
|
| 93 |
+
|
| 94 |
+
def make_adam(params):
|
| 95 |
+
return Adam(params, lr=lr)
|
| 96 |
+
|
| 97 |
+
optimizer = make_adam
|
| 98 |
+
return model, optimizer
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def get_lm_model(args, device, config):
|
| 102 |
+
"""Get language model(based on GPT-2) used for sequence prediction."""
|
| 103 |
+
|
| 104 |
+
ninp = config["ninp"]
|
| 105 |
+
nhead = config["nhead"]
|
| 106 |
+
initrange = config["initrange"]
|
| 107 |
+
dropout = config["dropout"]
|
| 108 |
+
vocab_size = config["vocab_size"]
|
| 109 |
+
nhid = config["nhid"]
|
| 110 |
+
ndecoder = config["num_decoder_layers"]
|
| 111 |
+
is_moe = config.get("is_moe", False)
|
| 112 |
+
num_local_experts = config.get("num_local_experts", 1)
|
| 113 |
+
|
| 114 |
+
if args.lazy_construction:
|
| 115 |
+
layers = [
|
| 116 |
+
LazyModule(lambda: transformer_lm.EmbeddingLayer(vocab_size, ninp, initrange)),
|
| 117 |
+
LazyModule(lambda: transformer_lm.PositionalEncodingLayer(ninp, dropout)),
|
| 118 |
+
]
|
| 119 |
+
for _ in range(ndecoder):
|
| 120 |
+
layers.append(
|
| 121 |
+
LazyModule(
|
| 122 |
+
lambda: transformer_lm.TransformerDecoderLayer(
|
| 123 |
+
ninp, nhead, nhid, dropout, is_moe, num_local_experts
|
| 124 |
+
)
|
| 125 |
+
)
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
layers.append(LazyModule(lambda: transformer_lm.LinearLayer(ninp, vocab_size, initrange)))
|
| 129 |
+
model = layers
|
| 130 |
+
else:
|
| 131 |
+
model = transformer_lm.TransformerLM(
|
| 132 |
+
vocab_size, ninp, nhead, nhid, dropout, initrange, ndecoder, is_moe, num_local_experts
|
| 133 |
+
).to(device)
|
| 134 |
+
|
| 135 |
+
return model
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def log_number_of_parameters(model, logger=None):
|
| 139 |
+
if not logger:
|
| 140 |
+
logger = logging
|
| 141 |
+
num_params = reduce(operator.add, (reduce(operator.mul, x.size()) for x in model.parameters()))
|
| 142 |
+
if hasattr(model, "group"):
|
| 143 |
+
total = torch.Tensor([num_params])
|
| 144 |
+
if torch.cuda.is_available():
|
| 145 |
+
total = total.cuda()
|
| 146 |
+
torch.distributed.all_reduce(total, group=model.group)
|
| 147 |
+
logger.debug(
|
| 148 |
+
f"training model, #params = {num_params}, group: {model.group.rank()}, grank:"
|
| 149 |
+
f" {torch.distributed.get_rank()}, sizes {model.group.size()}"
|
| 150 |
+
)
|
| 151 |
+
torch.distributed.barrier()
|
| 152 |
+
if model.group.rank() == 0:
|
| 153 |
+
logger.debug(f"total #prams = {total.item()}")
|
| 154 |
+
else:
|
| 155 |
+
logger.debug(f"training model, #params = {num_params}")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def get_dataset_info(args):
|
| 159 |
+
assert args.model_name == "lm"
|
| 160 |
+
if args.use_synthetic_data:
|
| 161 |
+
return wikitext2_data.get_synthetic_datasets()
|
| 162 |
+
else:
|
| 163 |
+
return wikitext2_data.get_real_datasets()
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def get_data_loader(dataset_info, args, benchmark_config, model_specs, num_replicas=1, rank=0):
|
| 167 |
+
return wikitext2_data.get_dataloaders(dataset_info, benchmark_config, model_specs, num_replicas, rank)
|
grounding-dino/.eval_venv/lib/python3.11/site-packages/cython.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
#
|
| 4 |
+
# Cython -- Main Program, generic
|
| 5 |
+
#
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
from typing import TYPE_CHECKING
|
| 9 |
+
except ImportError:
|
| 10 |
+
TYPE_CHECKING = False
|
| 11 |
+
|
| 12 |
+
if not TYPE_CHECKING and __name__ == '__main__':
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
# Make sure we import the right Cython
|
| 18 |
+
cythonpath, _ = os.path.split(os.path.realpath(__file__))
|
| 19 |
+
sys.path.insert(0, cythonpath)
|
| 20 |
+
|
| 21 |
+
from Cython.Compiler.Main import main
|
| 22 |
+
main(command_line = 1)
|
| 23 |
+
|
| 24 |
+
else:
|
| 25 |
+
# Void cython.* directives.
|
| 26 |
+
from Cython.Shadow import *
|
| 27 |
+
## and bring in the __version__
|
| 28 |
+
from Cython import __version__
|
| 29 |
+
from Cython import load_ipython_extension
|
grounding-dino/.eval_venv/pyvenv.cfg
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
home = /mnt/afs_agents/pangcong/miniconda3/envs/llamafac311/bin
|
| 2 |
+
include-system-site-packages = true
|
| 3 |
+
version = 3.11.14
|
| 4 |
+
executable = /mnt/afs_agents/pangcong/miniconda3/envs/llamafac311/bin/python3.11
|
| 5 |
+
command = /mnt/afs_agents/pangcong/miniconda3/envs/llamafac311/bin/python -m venv --system-site-packages /mnt/afs_agents/pangcong/workspace/fengxuyu_workspace/obj_det_val/grounding-dino/.eval_venv
|
grounding-dino/compute_recall_f1.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
基于 mmdet test.py 输出的 pkl 文件,计算每个类别的 Precision / Recall / F1
|
| 3 |
+
以及 Overall 的指标 (micro-average)。
|
| 4 |
+
|
| 5 |
+
用法:
|
| 6 |
+
python compute_recall_f1.py \
|
| 7 |
+
--config <config.py> \
|
| 8 |
+
--pkl <predictions.pkl> \
|
| 9 |
+
--score-thr 0.3 \
|
| 10 |
+
--iou-thr 0.5 \
|
| 11 |
+
--output metrics_report.txt
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import numpy as np
|
| 15 |
+
import mmengine
|
| 16 |
+
from mmengine.config import Config
|
| 17 |
+
from mmengine.registry import init_default_scope
|
| 18 |
+
from mmdet.registry import DATASETS
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def compute_iou_matrix(pred_bboxes, gt_bboxes):
|
| 22 |
+
"""计算 pred 和 gt 之间的 IoU 矩阵 [N_pred, N_gt]"""
|
| 23 |
+
if len(pred_bboxes) == 0 or len(gt_bboxes) == 0:
|
| 24 |
+
return np.zeros((len(pred_bboxes), len(gt_bboxes)))
|
| 25 |
+
|
| 26 |
+
pred = np.array(pred_bboxes)
|
| 27 |
+
gt = np.array(gt_bboxes)
|
| 28 |
+
|
| 29 |
+
x1 = np.maximum(pred[:, 0:1], gt[:, 0:1].T)
|
| 30 |
+
y1 = np.maximum(pred[:, 1:2], gt[:, 1:2].T)
|
| 31 |
+
x2 = np.minimum(pred[:, 2:3], gt[:, 2:3].T)
|
| 32 |
+
y2 = np.minimum(pred[:, 3:4], gt[:, 3:4].T)
|
| 33 |
+
|
| 34 |
+
inter = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0)
|
| 35 |
+
|
| 36 |
+
area_pred = (pred[:, 2] - pred[:, 0]) * (pred[:, 3] - pred[:, 1])
|
| 37 |
+
area_gt = (gt[:, 2] - gt[:, 0]) * (gt[:, 3] - gt[:, 1])
|
| 38 |
+
|
| 39 |
+
union = area_pred[:, None] + area_gt[None, :] - inter
|
| 40 |
+
iou = inter / np.maximum(union, 1e-6)
|
| 41 |
+
return iou
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def match_predictions(pred_bboxes, pred_labels, pred_scores,
|
| 45 |
+
gt_bboxes, gt_labels, iou_thr=0.5, score_thr=0.3):
|
| 46 |
+
"""
|
| 47 |
+
对单张图进行匹配, 返回每个类别的 TP / FP / FN 数量
|
| 48 |
+
"""
|
| 49 |
+
# 过滤低分预测
|
| 50 |
+
keep = pred_scores >= score_thr
|
| 51 |
+
pred_bboxes = pred_bboxes[keep]
|
| 52 |
+
pred_labels = pred_labels[keep]
|
| 53 |
+
pred_scores = pred_scores[keep]
|
| 54 |
+
|
| 55 |
+
# 按分数降序排列
|
| 56 |
+
order = np.argsort(-pred_scores)
|
| 57 |
+
pred_bboxes = pred_bboxes[order]
|
| 58 |
+
pred_labels = pred_labels[order]
|
| 59 |
+
|
| 60 |
+
gt_matched = np.zeros(len(gt_bboxes), dtype=bool)
|
| 61 |
+
|
| 62 |
+
tp = 0
|
| 63 |
+
fp = 0
|
| 64 |
+
|
| 65 |
+
per_class_tp = {}
|
| 66 |
+
per_class_fp = {}
|
| 67 |
+
per_class_fn = {}
|
| 68 |
+
|
| 69 |
+
# 计算 IoU 矩阵
|
| 70 |
+
if len(pred_bboxes) > 0 and len(gt_bboxes) > 0:
|
| 71 |
+
iou_matrix = compute_iou_matrix(pred_bboxes, gt_bboxes)
|
| 72 |
+
else:
|
| 73 |
+
iou_matrix = np.zeros((len(pred_bboxes), len(gt_bboxes)))
|
| 74 |
+
|
| 75 |
+
pred_matched = np.zeros(len(pred_bboxes), dtype=bool)
|
| 76 |
+
|
| 77 |
+
for i in range(len(pred_bboxes)):
|
| 78 |
+
pred_label = pred_labels[i]
|
| 79 |
+
# 找到同类别且未匹配的 GT
|
| 80 |
+
candidate_gt = np.where((gt_labels == pred_label) & (~gt_matched))[0]
|
| 81 |
+
|
| 82 |
+
if len(candidate_gt) == 0:
|
| 83 |
+
pred_matched[i] = False
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
ious = iou_matrix[i, candidate_gt]
|
| 87 |
+
best_idx = np.argmax(ious)
|
| 88 |
+
|
| 89 |
+
if ious[best_idx] >= iou_thr:
|
| 90 |
+
pred_matched[i] = True
|
| 91 |
+
gt_matched[candidate_gt[best_idx]] = True
|
| 92 |
+
else:
|
| 93 |
+
pred_matched[i] = False
|
| 94 |
+
|
| 95 |
+
# 统计每个类别
|
| 96 |
+
all_classes = set(pred_labels.tolist()) | set(gt_labels.tolist())
|
| 97 |
+
for cls in all_classes:
|
| 98 |
+
cls = int(cls)
|
| 99 |
+
cls_pred_mask = pred_labels == cls
|
| 100 |
+
cls_tp = int((cls_pred_mask & pred_matched).sum())
|
| 101 |
+
cls_fp = int((cls_pred_mask & ~pred_matched).sum())
|
| 102 |
+
cls_fn = int(((gt_labels == cls) & ~gt_matched).sum())
|
| 103 |
+
|
| 104 |
+
per_class_tp[cls] = per_class_tp.get(cls, 0) + cls_tp
|
| 105 |
+
per_class_fp[cls] = per_class_fp.get(cls, 0) + cls_fp
|
| 106 |
+
per_class_fn[cls] = per_class_fn.get(cls, 0) + cls_fn
|
| 107 |
+
|
| 108 |
+
return per_class_tp, per_class_fp, per_class_fn
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def main():
|
| 112 |
+
parser = argparse.ArgumentParser()
|
| 113 |
+
parser.add_argument('--config', required=True, help='Config file path')
|
| 114 |
+
parser.add_argument('--pkl', required=True, help='Prediction pkl file')
|
| 115 |
+
parser.add_argument('--score-thr', type=float, default=0.3)
|
| 116 |
+
parser.add_argument('--iou-thr', type=float, default=0.5)
|
| 117 |
+
parser.add_argument('--output', default=None, help='Output report file')
|
| 118 |
+
args = parser.parse_args()
|
| 119 |
+
|
| 120 |
+
cfg = Config.fromfile(args.config)
|
| 121 |
+
init_default_scope(cfg.get('default_scope', 'mmdet'))
|
| 122 |
+
|
| 123 |
+
# 构建数据集获取 GT
|
| 124 |
+
dataset = DATASETS.build(cfg.test_dataloader.dataset)
|
| 125 |
+
predictions = mmengine.load(args.pkl)
|
| 126 |
+
|
| 127 |
+
class_names = dataset.metainfo['classes']
|
| 128 |
+
num_classes = len(class_names)
|
| 129 |
+
|
| 130 |
+
# 累计统计
|
| 131 |
+
total_tp = {i: 0 for i in range(num_classes)}
|
| 132 |
+
total_fp = {i: 0 for i in range(num_classes)}
|
| 133 |
+
total_fn = {i: 0 for i in range(num_classes)}
|
| 134 |
+
|
| 135 |
+
print(f'>>> 评估参数: score_thr={args.score_thr}, iou_thr={args.iou_thr}')
|
| 136 |
+
print(f'>>> 共 {len(predictions)} 张图片')
|
| 137 |
+
|
| 138 |
+
for idx in range(len(predictions)):
|
| 139 |
+
pred = predictions[idx]
|
| 140 |
+
|
| 141 |
+
# 获取预测
|
| 142 |
+
pred_bboxes = pred['pred_instances']['bboxes'].cpu().numpy() \
|
| 143 |
+
if hasattr(pred['pred_instances']['bboxes'], 'cpu') \
|
| 144 |
+
else np.array(pred['pred_instances']['bboxes'])
|
| 145 |
+
pred_labels = pred['pred_instances']['labels'].cpu().numpy() \
|
| 146 |
+
if hasattr(pred['pred_instances']['labels'], 'cpu') \
|
| 147 |
+
else np.array(pred['pred_instances']['labels'])
|
| 148 |
+
pred_scores = pred['pred_instances']['scores'].cpu().numpy() \
|
| 149 |
+
if hasattr(pred['pred_instances']['scores'], 'cpu') \
|
| 150 |
+
else np.array(pred['pred_instances']['scores'])
|
| 151 |
+
|
| 152 |
+
# 获取 GT
|
| 153 |
+
data_info = dataset.get_data_info(idx)
|
| 154 |
+
gt_instances = data_info['instances']
|
| 155 |
+
if len(gt_instances) > 0:
|
| 156 |
+
gt_bboxes = np.array([inst['bbox'] for inst in gt_instances])
|
| 157 |
+
gt_labels = np.array([inst['bbox_label'] for inst in gt_instances])
|
| 158 |
+
# COCO 格式 bbox 是 [x,y,w,h],需转换为 [x1,y1,x2,y2]
|
| 159 |
+
if gt_bboxes.shape[1] == 4:
|
| 160 |
+
# 检查是否是 xywh 格式 (如果 w, h 值远小于 x2, y2 通常说明是 xyxy)
|
| 161 |
+
# mmdet CocoDataset 已经转换为 xyxy 了
|
| 162 |
+
pass
|
| 163 |
+
else:
|
| 164 |
+
gt_bboxes = np.zeros((0, 4))
|
| 165 |
+
gt_labels = np.array([], dtype=np.int64)
|
| 166 |
+
|
| 167 |
+
# 匹配
|
| 168 |
+
per_cls_tp, per_cls_fp, per_cls_fn = match_predictions(
|
| 169 |
+
pred_bboxes, pred_labels, pred_scores,
|
| 170 |
+
gt_bboxes, gt_labels,
|
| 171 |
+
iou_thr=args.iou_thr, score_thr=args.score_thr)
|
| 172 |
+
|
| 173 |
+
for cls in per_cls_tp:
|
| 174 |
+
if cls < num_classes:
|
| 175 |
+
total_tp[cls] += per_cls_tp[cls]
|
| 176 |
+
for cls in per_cls_fp:
|
| 177 |
+
if cls < num_classes:
|
| 178 |
+
total_fp[cls] += per_cls_fp[cls]
|
| 179 |
+
for cls in per_cls_fn:
|
| 180 |
+
if cls < num_classes:
|
| 181 |
+
total_fn[cls] += per_cls_fn[cls]
|
| 182 |
+
|
| 183 |
+
# 计算指标
|
| 184 |
+
lines = []
|
| 185 |
+
lines.append('=' * 80)
|
| 186 |
+
lines.append(f'Grounding DINO 评估报告 (score_thr={args.score_thr}, iou_thr={args.iou_thr})')
|
| 187 |
+
lines.append('=' * 80)
|
| 188 |
+
lines.append(f'{"类别":<20} {"TP":>6} {"FP":>6} {"FN":>6} {"Precision":>10} {"Recall":>10} {"F1":>10}')
|
| 189 |
+
lines.append('-' * 80)
|
| 190 |
+
|
| 191 |
+
all_tp = 0
|
| 192 |
+
all_fp = 0
|
| 193 |
+
all_fn = 0
|
| 194 |
+
|
| 195 |
+
for i in range(num_classes):
|
| 196 |
+
tp = total_tp[i]
|
| 197 |
+
fp = total_fp[i]
|
| 198 |
+
fn = total_fn[i]
|
| 199 |
+
|
| 200 |
+
precision = tp / max(tp + fp, 1)
|
| 201 |
+
recall = tp / max(tp + fn, 1)
|
| 202 |
+
f1 = 2 * precision * recall / max(precision + recall, 1e-6)
|
| 203 |
+
|
| 204 |
+
lines.append(f'{class_names[i]:<20} {tp:>6} {fp:>6} {fn:>6} {precision:>10.4f} {recall:>10.4f} {f1:>10.4f}')
|
| 205 |
+
|
| 206 |
+
all_tp += tp
|
| 207 |
+
all_fp += fp
|
| 208 |
+
all_fn += fn
|
| 209 |
+
|
| 210 |
+
# Overall (micro-average)
|
| 211 |
+
overall_precision = all_tp / max(all_tp + all_fp, 1)
|
| 212 |
+
overall_recall = all_tp / max(all_tp + all_fn, 1)
|
| 213 |
+
overall_f1 = 2 * overall_precision * overall_recall / max(overall_precision + overall_recall, 1e-6)
|
| 214 |
+
|
| 215 |
+
lines.append('-' * 80)
|
| 216 |
+
lines.append(f'{"Overall (micro)"::<20} {all_tp:>6} {all_fp:>6} {all_fn:>6} {overall_precision:>10.4f} {overall_recall:>10.4f} {overall_f1:>10.4f}')
|
| 217 |
+
lines.append('=' * 80)
|
| 218 |
+
|
| 219 |
+
report = '\n'.join(lines)
|
| 220 |
+
print(report)
|
| 221 |
+
|
| 222 |
+
if args.output:
|
| 223 |
+
with open(args.output, 'w') as f:
|
| 224 |
+
f.write(report)
|
| 225 |
+
print(f'\n>>> 报告已保存到: {args.output}')
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
if __name__ == '__main__':
|
| 229 |
+
main()
|
grounding-dino/convert_pkl_to_answer_jsonl.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert MMDetection prediction pkl to answer.jsonl-like format."""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, Iterable, List, Sequence
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
_BASE_DIR = Path(__file__).resolve().parent
|
| 16 |
+
DEFAULT_CONFIG = str(
|
| 17 |
+
_BASE_DIR
|
| 18 |
+
/ "work_dirs"
|
| 19 |
+
/ "mm_grounding_dino_traffic"
|
| 20 |
+
/ "grounding_dino_swin-t_finetune_traffic.py"
|
| 21 |
+
)
|
| 22 |
+
DEFAULT_PKL = str(_BASE_DIR / "eval_output" / "predictions.pkl")
|
| 23 |
+
DEFAULT_OUTPUT = str(_BASE_DIR / "eval_output" / "predictions_answer.jsonl")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _load_local_modules():
|
| 27 |
+
repo_root = Path(__file__).resolve().parent / "mmdetection"
|
| 28 |
+
if str(repo_root) not in sys.path:
|
| 29 |
+
sys.path.insert(0, str(repo_root))
|
| 30 |
+
|
| 31 |
+
import mmengine # type: ignore
|
| 32 |
+
from mmengine.config import Config # type: ignore
|
| 33 |
+
from mmengine.registry import init_default_scope # type: ignore
|
| 34 |
+
from mmdet.registry import DATASETS # type: ignore
|
| 35 |
+
|
| 36 |
+
return mmengine, Config, init_default_scope, DATASETS
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _to_numpy(data):
|
| 40 |
+
if data is None:
|
| 41 |
+
return None
|
| 42 |
+
if hasattr(data, "detach"):
|
| 43 |
+
data = data.detach()
|
| 44 |
+
if hasattr(data, "cpu"):
|
| 45 |
+
data = data.cpu()
|
| 46 |
+
if hasattr(data, "numpy"):
|
| 47 |
+
return data.numpy()
|
| 48 |
+
return np.asarray(data)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _get_field(obj, key):
|
| 52 |
+
if obj is None:
|
| 53 |
+
return None
|
| 54 |
+
if isinstance(obj, dict):
|
| 55 |
+
return obj.get(key)
|
| 56 |
+
if hasattr(obj, key):
|
| 57 |
+
return getattr(obj, key)
|
| 58 |
+
try:
|
| 59 |
+
return obj[key]
|
| 60 |
+
except Exception:
|
| 61 |
+
return None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _extract_pred_arrays(pred):
|
| 65 |
+
pred_instances = _get_field(pred, "pred_instances")
|
| 66 |
+
bboxes = _to_numpy(_get_field(pred_instances, "bboxes"))
|
| 67 |
+
labels = _to_numpy(_get_field(pred_instances, "labels"))
|
| 68 |
+
scores = _to_numpy(_get_field(pred_instances, "scores"))
|
| 69 |
+
|
| 70 |
+
if bboxes is None or labels is None or scores is None:
|
| 71 |
+
return (
|
| 72 |
+
np.zeros((0, 4), dtype=np.float32),
|
| 73 |
+
np.zeros((0,), dtype=np.int64),
|
| 74 |
+
np.zeros((0,), dtype=np.float32),
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
return (
|
| 78 |
+
np.asarray(bboxes, dtype=np.float32),
|
| 79 |
+
np.asarray(labels, dtype=np.int64),
|
| 80 |
+
np.asarray(scores, dtype=np.float32),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _resolve_image_path(data_info):
|
| 85 |
+
for key in ("img_path", "image_path", "file_name", "filename"):
|
| 86 |
+
value = data_info.get(key)
|
| 87 |
+
if value:
|
| 88 |
+
return str(value)
|
| 89 |
+
return ""
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _to_xyxy(box):
|
| 93 |
+
if box is None or len(box) < 4:
|
| 94 |
+
return None
|
| 95 |
+
return [float(box[0]), float(box[1]), float(box[2]), float(box[3])]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _resolve_image_size(data_info):
|
| 99 |
+
if "ori_shape" in data_info and data_info["ori_shape"] is not None:
|
| 100 |
+
ori_shape = data_info["ori_shape"]
|
| 101 |
+
if len(ori_shape) >= 2:
|
| 102 |
+
return int(ori_shape[1]), int(ori_shape[0])
|
| 103 |
+
if "width" in data_info and "height" in data_info:
|
| 104 |
+
return int(data_info["width"]), int(data_info["height"])
|
| 105 |
+
return None, None
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _build_question(class_names: Sequence[str]) -> str:
|
| 109 |
+
categories = ", ".join(class_names)
|
| 110 |
+
return (
|
| 111 |
+
f"Detect {categories}. If an object is present, output its bounding box "
|
| 112 |
+
"in [x0, y0, x1, y1] format. If a category is not present, output None."
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _coord_to_bin(value: float, size: int) -> int:
|
| 117 |
+
if size <= 1:
|
| 118 |
+
return 0
|
| 119 |
+
value = max(0.0, min(float(value), float(size)))
|
| 120 |
+
if value == size:
|
| 121 |
+
value = size - 1e-6
|
| 122 |
+
return int(round(value / size * 999.0))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _boxes_to_raw_segment(category: str, boxes: List[List[float]], width: int, height: int) -> str:
|
| 126 |
+
if not boxes:
|
| 127 |
+
body = " None "
|
| 128 |
+
else:
|
| 129 |
+
encoded_boxes = []
|
| 130 |
+
for box in boxes:
|
| 131 |
+
x0, y0, x1, y1 = box[:4]
|
| 132 |
+
encoded_boxes.append(
|
| 133 |
+
" <{}> <{}> <{}> <{}> ".format(
|
| 134 |
+
_coord_to_bin(x0, width),
|
| 135 |
+
_coord_to_bin(y0, height),
|
| 136 |
+
_coord_to_bin(x1, width),
|
| 137 |
+
_coord_to_bin(y1, height),
|
| 138 |
+
)
|
| 139 |
+
)
|
| 140 |
+
body = " , ".join(encoded_boxes)
|
| 141 |
+
return (
|
| 142 |
+
f"<|object_ref_start|> {category} <|object_ref_end|> "
|
| 143 |
+
f"<|box_start|> {body} <|box_end|>"
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _build_raw_response(pred_dict: Dict[str, List[List[float]]], class_names: Sequence[str], width: int, height: int) -> str:
|
| 148 |
+
hit_categories = [name for name in class_names if pred_dict.get(name)]
|
| 149 |
+
total_objects = sum(len(pred_dict.get(name, [])) for name in class_names)
|
| 150 |
+
|
| 151 |
+
summary_parts = [
|
| 152 |
+
"I have carefully scanned the entire image for all target categories.",
|
| 153 |
+
f"I found {total_objects} objects across {len(hit_categories)} categories.",
|
| 154 |
+
]
|
| 155 |
+
for name in class_names:
|
| 156 |
+
count = len(pred_dict.get(name, []))
|
| 157 |
+
if count > 0:
|
| 158 |
+
summary_parts.append(f"Detected {count} {name}(s).")
|
| 159 |
+
|
| 160 |
+
raw_segments = [
|
| 161 |
+
_boxes_to_raw_segment(name, pred_dict.get(name, []), width, height)
|
| 162 |
+
for name in class_names
|
| 163 |
+
]
|
| 164 |
+
return "<think> " + " ".join(summary_parts) + " </think>\n\n " + " , ".join(raw_segments)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _build_gt_dict(data_info: dict, class_names: Sequence[str]) -> Dict[str, List[List[float]]]:
|
| 168 |
+
gt_dict = {class_name: [] for class_name in class_names}
|
| 169 |
+
for inst in data_info.get("instances", []):
|
| 170 |
+
label = inst.get("bbox_label")
|
| 171 |
+
if label is None:
|
| 172 |
+
label = inst.get("label")
|
| 173 |
+
if label is None:
|
| 174 |
+
continue
|
| 175 |
+
|
| 176 |
+
label = int(label)
|
| 177 |
+
if label < 0 or label >= len(class_names):
|
| 178 |
+
continue
|
| 179 |
+
|
| 180 |
+
bbox = _to_xyxy(inst.get("bbox"))
|
| 181 |
+
if bbox is None:
|
| 182 |
+
continue
|
| 183 |
+
gt_dict[class_names[label]].append(bbox)
|
| 184 |
+
return gt_dict
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _build_pred_dict(pred, class_names: Sequence[str], score_thr: float) -> Dict[str, List[List[float]]]:
|
| 188 |
+
pred_dict = {class_name: [] for class_name in class_names}
|
| 189 |
+
bboxes, labels, scores = _extract_pred_arrays(pred)
|
| 190 |
+
if scores.size == 0:
|
| 191 |
+
return pred_dict
|
| 192 |
+
|
| 193 |
+
order = np.argsort(-scores)
|
| 194 |
+
for idx in order.tolist():
|
| 195 |
+
score = float(scores[idx])
|
| 196 |
+
if score < score_thr:
|
| 197 |
+
break
|
| 198 |
+
label = int(labels[idx])
|
| 199 |
+
if label < 0 or label >= len(class_names):
|
| 200 |
+
continue
|
| 201 |
+
bbox = _to_xyxy(bboxes[idx])
|
| 202 |
+
if bbox is None:
|
| 203 |
+
continue
|
| 204 |
+
pred_dict[class_names[label]].append(bbox)
|
| 205 |
+
return pred_dict
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _build_rows(dataset, predictions, class_names: Sequence[str], score_thr: float, dataset_name: str) -> List[dict]:
|
| 209 |
+
rows = []
|
| 210 |
+
question = _build_question(class_names)
|
| 211 |
+
sample_count = min(len(dataset), len(predictions))
|
| 212 |
+
if len(dataset) != len(predictions):
|
| 213 |
+
print(
|
| 214 |
+
f"[Warn] dataset size ({len(dataset)}) != predictions size ({len(predictions)}), "
|
| 215 |
+
f"using first {sample_count} samples."
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
for idx in range(sample_count):
|
| 219 |
+
data_info = dataset.get_data_info(idx)
|
| 220 |
+
image_path = _resolve_image_path(data_info)
|
| 221 |
+
width, height = _resolve_image_size(data_info)
|
| 222 |
+
if width is None or height is None:
|
| 223 |
+
raise ValueError(f"Cannot resolve image size for sample {idx}: {image_path}")
|
| 224 |
+
|
| 225 |
+
pred_dict = _build_pred_dict(predictions[idx], class_names, score_thr)
|
| 226 |
+
gt_dict = _build_gt_dict(data_info, class_names)
|
| 227 |
+
raw_response = _build_raw_response(pred_dict, class_names, width, height)
|
| 228 |
+
|
| 229 |
+
rows.append(
|
| 230 |
+
{
|
| 231 |
+
"image_path": image_path,
|
| 232 |
+
"extracted_predictions": pred_dict,
|
| 233 |
+
"gt": gt_dict,
|
| 234 |
+
"question": question,
|
| 235 |
+
"dataset_name": dataset_name,
|
| 236 |
+
"raw_response": raw_response,
|
| 237 |
+
"task_name": "common_object_detection",
|
| 238 |
+
}
|
| 239 |
+
)
|
| 240 |
+
return rows
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def parse_args():
|
| 244 |
+
parser = argparse.ArgumentParser(
|
| 245 |
+
description="Convert MMDetection predictions.pkl to answer.jsonl-like format."
|
| 246 |
+
)
|
| 247 |
+
parser.add_argument("--config", default=DEFAULT_CONFIG, help="MMDetection config path")
|
| 248 |
+
parser.add_argument("--pkl", default=DEFAULT_PKL, help="MMDetection prediction pkl path")
|
| 249 |
+
parser.add_argument("--output-jsonl", default=DEFAULT_OUTPUT, help="Output answer-style jsonl")
|
| 250 |
+
parser.add_argument("--score-thr", type=float, default=0.3, help="Prediction score threshold")
|
| 251 |
+
parser.add_argument(
|
| 252 |
+
"--dataset-name",
|
| 253 |
+
default="Traffic_Dataset",
|
| 254 |
+
help="dataset_name field in the output jsonl",
|
| 255 |
+
)
|
| 256 |
+
return parser.parse_args()
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def main():
|
| 260 |
+
args = parse_args()
|
| 261 |
+
output_dir = os.path.dirname(args.output_jsonl)
|
| 262 |
+
if output_dir:
|
| 263 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 264 |
+
|
| 265 |
+
mmengine, Config, init_default_scope, DATASETS = _load_local_modules()
|
| 266 |
+
|
| 267 |
+
print(f"[Info] Loading config: {args.config}")
|
| 268 |
+
cfg = Config.fromfile(args.config)
|
| 269 |
+
init_default_scope(cfg.get("default_scope", "mmdet"))
|
| 270 |
+
|
| 271 |
+
print("[Info] Building test dataset...")
|
| 272 |
+
dataset = DATASETS.build(cfg.test_dataloader.dataset)
|
| 273 |
+
class_names = tuple(dataset.metainfo["classes"])
|
| 274 |
+
print(f"[Info] Classes ({len(class_names)}): {class_names}")
|
| 275 |
+
|
| 276 |
+
print(f"[Info] Loading predictions: {args.pkl}")
|
| 277 |
+
predictions = mmengine.load(args.pkl)
|
| 278 |
+
|
| 279 |
+
print("[Info] Converting to answer.jsonl-like rows...")
|
| 280 |
+
rows = _build_rows(
|
| 281 |
+
dataset=dataset,
|
| 282 |
+
predictions=predictions,
|
| 283 |
+
class_names=class_names,
|
| 284 |
+
score_thr=args.score_thr,
|
| 285 |
+
dataset_name=args.dataset_name,
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
with open(args.output_jsonl, "w", encoding="utf-8") as f:
|
| 289 |
+
for row in rows:
|
| 290 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 291 |
+
|
| 292 |
+
print(f"[Info] Saved {len(rows)} rows to: {args.output_jsonl}")
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
if __name__ == "__main__":
|
| 296 |
+
main()
|
grounding-dino/data_precess_train.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import cv2
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
# ================= 配置区域 =================
|
| 7 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 8 |
+
WORKSPACE_DIR = BASE_DIR.parent.parent
|
| 9 |
+
jsonl_file = str(WORKSPACE_DIR / 'rex_data' / 'data' / 'rex-omni-data' / 'train' / 'merged_shuffled_no_rect_from_wuhan_plus_replenish_mixed_vis_temp_empty_gt.jsonl') # 你的原始数据路径
|
| 10 |
+
output_dir = str(BASE_DIR / 'dataset') # 输出文件夹名
|
| 11 |
+
json_name = 'train_traffic_data_2_25.json' # 输出的 json 文件名
|
| 12 |
+
# 统一图片根目录:新文件里有多个子目录(如 PanoImages_data_all / crops_scaled1p5 / crop_empty)
|
| 13 |
+
img_root = str(WORKSPACE_DIR / 'rex_data' / 'data')
|
| 14 |
+
# 当图片不在 img_root 下时,是否允许在 COCO 的 file_name 里写绝对路径
|
| 15 |
+
allow_absolute_file_name = True
|
| 16 |
+
|
| 17 |
+
# 类别映射 (MMDet 中 ID 建议从 1 开始,或者保持 0,CocoDataset默认兼容)
|
| 18 |
+
# 这里的顺序非常重要,必须和后面 Config 里的 class_name 顺序一致
|
| 19 |
+
categories = [
|
| 20 |
+
{"id": 0, "name": "traffic sign"},
|
| 21 |
+
{"id": 1, "name": "street light"},
|
| 22 |
+
{"id": 2, "name": "traffic light"},
|
| 23 |
+
{"id": 3, "name": "surveillance camera"},
|
| 24 |
+
{"id": 4, "name": "ball bollard"},
|
| 25 |
+
{"id": 5, "name": "fire hydrant"},
|
| 26 |
+
{"id": 6, "name": "trash bin"},
|
| 27 |
+
{"id": 7, "name": "manhole"},
|
| 28 |
+
{"id": 8, "name": "traffic cone"},
|
| 29 |
+
{"id": 9, "name": "bollard"}
|
| 30 |
+
]
|
| 31 |
+
# ===========================================
|
| 32 |
+
|
| 33 |
+
def resolve_image_path(raw_path):
|
| 34 |
+
"""支持绝对路径和相对路径(相对 jsonl 或相对 img_root)。"""
|
| 35 |
+
if not raw_path:
|
| 36 |
+
return None
|
| 37 |
+
raw_path = os.path.expanduser(str(raw_path))
|
| 38 |
+
if os.path.isabs(raw_path):
|
| 39 |
+
return raw_path
|
| 40 |
+
|
| 41 |
+
candidates = [
|
| 42 |
+
os.path.join(os.path.dirname(jsonl_file), raw_path),
|
| 43 |
+
os.path.join(img_root, raw_path)
|
| 44 |
+
]
|
| 45 |
+
for p in candidates:
|
| 46 |
+
if os.path.exists(p):
|
| 47 |
+
return os.path.abspath(p)
|
| 48 |
+
return os.path.abspath(candidates[0])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def build_file_name(img_path):
|
| 52 |
+
"""优先写相对 img_root 的路径;不在 img_root 下时可回退到绝对路径。"""
|
| 53 |
+
rel_path = os.path.relpath(img_path, img_root)
|
| 54 |
+
if not rel_path.startswith('..'):
|
| 55 |
+
return rel_path.replace('\\', '/')
|
| 56 |
+
if allow_absolute_file_name:
|
| 57 |
+
return os.path.abspath(img_path).replace('\\', '/')
|
| 58 |
+
return None
|
| 59 |
+
|
| 60 |
+
def main():
|
| 61 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 62 |
+
dst_img_dir = os.path.join(output_dir, 'images')
|
| 63 |
+
os.makedirs(dst_img_dir, exist_ok=True)
|
| 64 |
+
|
| 65 |
+
images = []
|
| 66 |
+
annotations = []
|
| 67 |
+
|
| 68 |
+
# 建立名字到ID的映射
|
| 69 |
+
cat_map = {cat['name']: cat['id'] for cat in categories}
|
| 70 |
+
|
| 71 |
+
print(f"Reading {jsonl_file}...")
|
| 72 |
+
|
| 73 |
+
data_lines = []
|
| 74 |
+
with open(jsonl_file, 'r', encoding='utf-8') as f:
|
| 75 |
+
for line in f:
|
| 76 |
+
if line.strip():
|
| 77 |
+
data_lines.append(json.loads(line))
|
| 78 |
+
|
| 79 |
+
print(f"Converting {len(data_lines)} images to COCO format...")
|
| 80 |
+
|
| 81 |
+
ann_id = 0
|
| 82 |
+
img_id = 0
|
| 83 |
+
|
| 84 |
+
for entry in data_lines:
|
| 85 |
+
raw_img_path = entry.get('image_name') or entry.get('image_path')
|
| 86 |
+
img_path = resolve_image_path(raw_img_path)
|
| 87 |
+
if not img_path:
|
| 88 |
+
continue
|
| 89 |
+
|
| 90 |
+
# 1. 检查并读取图片 (需要宽高)
|
| 91 |
+
if not os.path.exists(img_path):
|
| 92 |
+
print(f"Skip: {img_path} not found")
|
| 93 |
+
continue
|
| 94 |
+
|
| 95 |
+
img = cv2.imread(img_path)
|
| 96 |
+
if img is None: continue
|
| 97 |
+
h, w = img.shape[:2]
|
| 98 |
+
|
| 99 |
+
file_name = build_file_name(img_path)
|
| 100 |
+
if file_name is None:
|
| 101 |
+
print(f"Skip: {img_path} is outside img_root={img_root}")
|
| 102 |
+
continue
|
| 103 |
+
|
| 104 |
+
# 2. 这里的策略是:不复制图片,直接用软链接,或者在 config 里指定原图路径
|
| 105 |
+
# 为了方便,这里我们假设你不想复制几千张图,所以只生成 JSON
|
| 106 |
+
# Config 里的 data_prefix 需要指向原图所在的【父目录】
|
| 107 |
+
|
| 108 |
+
images.append({
|
| 109 |
+
"id": img_id,
|
| 110 |
+
"file_name": file_name, # 存相对 img_root 的路径,避免同名文件冲突
|
| 111 |
+
"height": h,
|
| 112 |
+
"width": w
|
| 113 |
+
})
|
| 114 |
+
|
| 115 |
+
# 3. 处理标注
|
| 116 |
+
boxes = entry.get('annotation', {}).get('boxes', [])
|
| 117 |
+
for box_item in boxes:
|
| 118 |
+
phrase = box_item.get('phrase')
|
| 119 |
+
bbox = box_item.get('bbox') # [x1, y1, x2, y2]
|
| 120 |
+
|
| 121 |
+
if phrase not in cat_map:
|
| 122 |
+
continue
|
| 123 |
+
|
| 124 |
+
cat_id = cat_map[phrase]
|
| 125 |
+
|
| 126 |
+
if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
|
| 127 |
+
continue
|
| 128 |
+
|
| 129 |
+
# 坐标转换: xyxy -> xywh
|
| 130 |
+
x1, y1, x2, y2 = map(float, bbox)
|
| 131 |
+
coco_w = x2 - x1
|
| 132 |
+
coco_h = y2 - y1
|
| 133 |
+
if coco_w <= 0 or coco_h <= 0:
|
| 134 |
+
continue
|
| 135 |
+
|
| 136 |
+
annotations.append({
|
| 137 |
+
"id": ann_id,
|
| 138 |
+
"image_id": img_id,
|
| 139 |
+
"category_id": cat_id,
|
| 140 |
+
"bbox": [x1, y1, coco_w, coco_h],
|
| 141 |
+
"area": coco_w * coco_h,
|
| 142 |
+
"iscrowd": 0
|
| 143 |
+
})
|
| 144 |
+
ann_id += 1
|
| 145 |
+
|
| 146 |
+
img_id += 1
|
| 147 |
+
|
| 148 |
+
# 简单打印进度
|
| 149 |
+
if img_id % 500 == 0:
|
| 150 |
+
print(f"Processed {img_id}...")
|
| 151 |
+
|
| 152 |
+
# 构建最终字典
|
| 153 |
+
coco_output = {
|
| 154 |
+
"images": images,
|
| 155 |
+
"annotations": annotations,
|
| 156 |
+
"categories": categories
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
save_path = os.path.join(output_dir, json_name)
|
| 160 |
+
with open(save_path, 'w') as f:
|
| 161 |
+
json.dump(coco_output, f)
|
| 162 |
+
|
| 163 |
+
print(f"Done! Saved to {save_path}")
|
| 164 |
+
print(f"Total Images: {len(images)}, Total Annotations: {len(annotations)}")
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
main()
|
grounding-dino/data_precess_val.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
# ================= 配置区域 =================
|
| 8 |
+
# 1. 你的验证集文件路径
|
| 9 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 10 |
+
WORKSPACE_DIR = BASE_DIR.parent.parent
|
| 11 |
+
val_jsonl_path = str(WORKSPACE_DIR / 'rex_data' / 'data' / 'rex-omni-data' / 'train' / 'merged_all_rect_img_dir_plus_road_detection_eval_filtered_0.4.jsonl')
|
| 12 |
+
|
| 13 |
+
# 2. 输出的 COCO 格式 json 路径
|
| 14 |
+
output_json_path = str(BASE_DIR / 'dataset' / 'val_traffic_data_2_25.json')
|
| 15 |
+
img_root = str(WORKSPACE_DIR / 'rex_data' / 'data' / 'PanoImages_data_all') # 图片统一根目录
|
| 16 |
+
|
| 17 |
+
# 3. 类别映射 (⚠️必须与训练时的 ID 严格一致!)
|
| 18 |
+
# 如果你训练时 traffic light 是 0,这里也必须是 0
|
| 19 |
+
categories_info = [
|
| 20 |
+
{"id": 0, "name": "traffic sign"},
|
| 21 |
+
{"id": 1, "name": "street light"},
|
| 22 |
+
{"id": 2, "name": "traffic light"},
|
| 23 |
+
{"id": 3, "name": "surveillance camera"},
|
| 24 |
+
{"id": 4, "name": "ball bollard"},
|
| 25 |
+
{"id": 5, "name": "fire hydrant"},
|
| 26 |
+
{"id": 6, "name": "trash bin"},
|
| 27 |
+
{"id": 7, "name": "manhole"},
|
| 28 |
+
{"id": 8, "name": "traffic cone"},
|
| 29 |
+
{"id": 9, "name": "bollard"}
|
| 30 |
+
]
|
| 31 |
+
# ===========================================
|
| 32 |
+
|
| 33 |
+
def main():
|
| 34 |
+
# 准备 COCO 基础结构
|
| 35 |
+
coco_output = {
|
| 36 |
+
"images": [],
|
| 37 |
+
"annotations": [],
|
| 38 |
+
"categories": categories_info
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
# 建立 类别名 -> ID 的快速查询字典
|
| 42 |
+
cat_name_to_id = {cat['name']: cat['id'] for cat in categories_info}
|
| 43 |
+
|
| 44 |
+
img_id_counter = 0
|
| 45 |
+
ann_id_counter = 0
|
| 46 |
+
|
| 47 |
+
print(f"Reading validation data from {val_jsonl_path}...")
|
| 48 |
+
|
| 49 |
+
with open(val_jsonl_path, 'r', encoding='utf-8') as f:
|
| 50 |
+
lines = f.readlines()
|
| 51 |
+
|
| 52 |
+
print(f"Processing {len(lines)} images...")
|
| 53 |
+
|
| 54 |
+
for line in lines:
|
| 55 |
+
if not line.strip():
|
| 56 |
+
continue
|
| 57 |
+
|
| 58 |
+
entry = json.loads(line)
|
| 59 |
+
|
| 60 |
+
# 1. 获取图片信息
|
| 61 |
+
img_path = entry.get('image_path')
|
| 62 |
+
if not img_path:
|
| 63 |
+
print(f"[Skip] Missing image_path in line")
|
| 64 |
+
continue
|
| 65 |
+
|
| 66 |
+
# 验证图片是否存在 (需要读取宽高)
|
| 67 |
+
if not os.path.exists(img_path):
|
| 68 |
+
print(f"[Warn] Image not found: {img_path}")
|
| 69 |
+
continue
|
| 70 |
+
|
| 71 |
+
img = cv2.imread(img_path)
|
| 72 |
+
if img is None:
|
| 73 |
+
print(f"[Warn] Cannot read image: {img_path}")
|
| 74 |
+
continue
|
| 75 |
+
|
| 76 |
+
h, w = img.shape[:2]
|
| 77 |
+
rel_path = os.path.relpath(img_path, img_root)
|
| 78 |
+
if rel_path.startswith('..'):
|
| 79 |
+
print(f"[Skip] Image path outside img_root: {img_path}")
|
| 80 |
+
continue
|
| 81 |
+
file_name = rel_path.replace('\\', '/')
|
| 82 |
+
|
| 83 |
+
# 添加图片信息
|
| 84 |
+
image_info = {
|
| 85 |
+
"id": img_id_counter,
|
| 86 |
+
"file_name": file_name, # 存相对 img_root 的路径,避免同名文件冲突
|
| 87 |
+
"height": h,
|
| 88 |
+
"width": w
|
| 89 |
+
}
|
| 90 |
+
coco_output["images"].append(image_info)
|
| 91 |
+
|
| 92 |
+
# 2. 处理标注 (解析 gt 字典)
|
| 93 |
+
# 格式: "gt": {"traffic light": [[x1, y1, x2, y2], ...], ...}
|
| 94 |
+
gt_dict = entry.get('gt', {})
|
| 95 |
+
|
| 96 |
+
for class_name, bboxes in gt_dict.items():
|
| 97 |
+
# 过滤掉不需要的类别
|
| 98 |
+
if class_name not in cat_name_to_id:
|
| 99 |
+
continue
|
| 100 |
+
|
| 101 |
+
cat_id = cat_name_to_id[class_name]
|
| 102 |
+
|
| 103 |
+
for bbox in bboxes:
|
| 104 |
+
# 确保 bbox 格式正确
|
| 105 |
+
if len(bbox) != 4:
|
| 106 |
+
continue
|
| 107 |
+
|
| 108 |
+
x1, y1, x2, y2 = bbox
|
| 109 |
+
|
| 110 |
+
# 转换: xyxy -> xywh
|
| 111 |
+
coco_w = x2 - x1
|
| 112 |
+
coco_h = y2 - y1
|
| 113 |
+
coco_x = x1
|
| 114 |
+
coco_y = y1
|
| 115 |
+
|
| 116 |
+
# 添加标注信息
|
| 117 |
+
ann_info = {
|
| 118 |
+
"id": ann_id_counter,
|
| 119 |
+
"image_id": img_id_counter,
|
| 120 |
+
"category_id": cat_id,
|
| 121 |
+
"bbox": [coco_x, coco_y, coco_w, coco_h],
|
| 122 |
+
"area": coco_w * coco_h,
|
| 123 |
+
"iscrowd": 0
|
| 124 |
+
}
|
| 125 |
+
coco_output["annotations"].append(ann_info)
|
| 126 |
+
ann_id_counter += 1
|
| 127 |
+
|
| 128 |
+
img_id_counter += 1
|
| 129 |
+
if img_id_counter % 100 == 0:
|
| 130 |
+
print(f"Processed {img_id_counter} images...")
|
| 131 |
+
|
| 132 |
+
# 保存结果
|
| 133 |
+
os.makedirs(os.path.dirname(output_json_path), exist_ok=True)
|
| 134 |
+
with open(output_json_path, 'w') as f:
|
| 135 |
+
json.dump(coco_output, f)
|
| 136 |
+
|
| 137 |
+
print(f"Conversion Done! Saved to {output_json_path}")
|
| 138 |
+
print(f"Images: {len(coco_output['images'])}, Annotations: {len(coco_output['annotations'])}")
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
main()
|
grounding-dino/evaluate_with_rex_omni.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Convert MMDetection test pkl predictions to Rex-Omni evaluate.py jsonl format,
|
| 4 |
+
then run Rex-Omni evaluation logic (large/small object split IoU evaluation).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import importlib.util
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import mmengine
|
| 15 |
+
import numpy as np
|
| 16 |
+
from mmengine.config import Config
|
| 17 |
+
from mmengine.registry import init_default_scope
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_BASE_DIR = Path(__file__).resolve().parent
|
| 21 |
+
DEFAULT_REX_EVAL_SCRIPT = str(
|
| 22 |
+
_BASE_DIR.parent.parent / "Rex-Omni_bxd" / "evaluation" / "evaluate.py"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _to_numpy(data):
|
| 27 |
+
if data is None:
|
| 28 |
+
return None
|
| 29 |
+
if hasattr(data, "detach"):
|
| 30 |
+
data = data.detach()
|
| 31 |
+
if hasattr(data, "cpu"):
|
| 32 |
+
data = data.cpu()
|
| 33 |
+
if hasattr(data, "numpy"):
|
| 34 |
+
return data.numpy()
|
| 35 |
+
return np.asarray(data)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _get_field(obj, key):
|
| 39 |
+
if obj is None:
|
| 40 |
+
return None
|
| 41 |
+
if isinstance(obj, dict):
|
| 42 |
+
return obj.get(key)
|
| 43 |
+
if hasattr(obj, key):
|
| 44 |
+
return getattr(obj, key)
|
| 45 |
+
try:
|
| 46 |
+
return obj[key]
|
| 47 |
+
except Exception:
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _extract_pred_arrays(pred):
|
| 52 |
+
pred_instances = _get_field(pred, "pred_instances")
|
| 53 |
+
bboxes = _to_numpy(_get_field(pred_instances, "bboxes"))
|
| 54 |
+
labels = _to_numpy(_get_field(pred_instances, "labels"))
|
| 55 |
+
scores = _to_numpy(_get_field(pred_instances, "scores"))
|
| 56 |
+
|
| 57 |
+
if bboxes is None or labels is None or scores is None:
|
| 58 |
+
return (
|
| 59 |
+
np.zeros((0, 4), dtype=np.float32),
|
| 60 |
+
np.zeros((0,), dtype=np.int64),
|
| 61 |
+
np.zeros((0,), dtype=np.float32),
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
bboxes = np.asarray(bboxes, dtype=np.float32)
|
| 65 |
+
labels = np.asarray(labels, dtype=np.int64)
|
| 66 |
+
scores = np.asarray(scores, dtype=np.float32)
|
| 67 |
+
return bboxes, labels, scores
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _resolve_image_path(data_info):
|
| 71 |
+
for key in ("img_path", "image_path", "file_name", "filename"):
|
| 72 |
+
value = data_info.get(key)
|
| 73 |
+
if value:
|
| 74 |
+
return str(value)
|
| 75 |
+
return ""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _to_xyxy(box):
|
| 79 |
+
if box is None or len(box) < 4:
|
| 80 |
+
return None
|
| 81 |
+
return [float(box[0]), float(box[1]), float(box[2]), float(box[3])]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _build_eval_rows(dataset, predictions, class_names, score_thr):
|
| 85 |
+
rows = []
|
| 86 |
+
sample_count = min(len(dataset), len(predictions))
|
| 87 |
+
if len(dataset) != len(predictions):
|
| 88 |
+
print(
|
| 89 |
+
f"[Warn] dataset size ({len(dataset)}) != predictions size ({len(predictions)}), "
|
| 90 |
+
f"using first {sample_count} samples."
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
for idx in range(sample_count):
|
| 94 |
+
pred_bboxes, pred_labels, pred_scores = _extract_pred_arrays(predictions[idx])
|
| 95 |
+
order = np.argsort(-pred_scores) if pred_scores.size > 0 else np.array([], dtype=np.int64)
|
| 96 |
+
|
| 97 |
+
pred_dict = {}
|
| 98 |
+
for rank in order.tolist():
|
| 99 |
+
if pred_scores[rank] < score_thr:
|
| 100 |
+
break
|
| 101 |
+
|
| 102 |
+
label = int(pred_labels[rank])
|
| 103 |
+
if label < 0 or label >= len(class_names):
|
| 104 |
+
continue
|
| 105 |
+
class_name = class_names[label]
|
| 106 |
+
box_xyxy = _to_xyxy(pred_bboxes[rank])
|
| 107 |
+
if box_xyxy is None:
|
| 108 |
+
continue
|
| 109 |
+
|
| 110 |
+
pred_dict.setdefault(class_name, []).append(box_xyxy)
|
| 111 |
+
|
| 112 |
+
data_info = dataset.get_data_info(idx)
|
| 113 |
+
image_path = _resolve_image_path(data_info)
|
| 114 |
+
|
| 115 |
+
gt_dict = {}
|
| 116 |
+
instances = data_info.get("instances", [])
|
| 117 |
+
for inst in instances:
|
| 118 |
+
label = inst.get("bbox_label")
|
| 119 |
+
if label is None:
|
| 120 |
+
label = inst.get("label")
|
| 121 |
+
if label is None:
|
| 122 |
+
continue
|
| 123 |
+
|
| 124 |
+
label = int(label)
|
| 125 |
+
if label < 0 or label >= len(class_names):
|
| 126 |
+
continue
|
| 127 |
+
|
| 128 |
+
box_xyxy = _to_xyxy(inst.get("bbox"))
|
| 129 |
+
if box_xyxy is None:
|
| 130 |
+
continue
|
| 131 |
+
|
| 132 |
+
class_name = class_names[label]
|
| 133 |
+
gt_dict.setdefault(class_name, []).append(box_xyxy)
|
| 134 |
+
|
| 135 |
+
categories = sorted(set(pred_dict.keys()) | set(gt_dict.keys()))
|
| 136 |
+
rows.append(
|
| 137 |
+
{
|
| 138 |
+
"image_path": image_path,
|
| 139 |
+
"categories": categories,
|
| 140 |
+
"extracted_predictions": pred_dict,
|
| 141 |
+
"gt": gt_dict,
|
| 142 |
+
"dataset_name": "GroundingDINO",
|
| 143 |
+
"task_name": "common_object_detection",
|
| 144 |
+
}
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
return rows
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _load_rex_evaluate_fn(rex_eval_script):
|
| 151 |
+
eval_path = Path(rex_eval_script)
|
| 152 |
+
if not eval_path.exists():
|
| 153 |
+
raise FileNotFoundError(f"Rex evaluate.py not found: {eval_path}")
|
| 154 |
+
|
| 155 |
+
spec = importlib.util.spec_from_file_location("rex_omni_eval_module", str(eval_path))
|
| 156 |
+
module = importlib.util.module_from_spec(spec)
|
| 157 |
+
assert spec.loader is not None
|
| 158 |
+
spec.loader.exec_module(module)
|
| 159 |
+
|
| 160 |
+
if not hasattr(module, "evaluate_jsonl"):
|
| 161 |
+
raise AttributeError(f"evaluate_jsonl not found in: {eval_path}")
|
| 162 |
+
return module.evaluate_jsonl
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _load_datasets_registry():
|
| 166 |
+
try:
|
| 167 |
+
from mmdet.registry import DATASETS # type: ignore
|
| 168 |
+
return DATASETS
|
| 169 |
+
except ModuleNotFoundError:
|
| 170 |
+
local_mmdet_root = Path(__file__).resolve().parent / "mmdetection"
|
| 171 |
+
local_mmdet_pkg = local_mmdet_root / "mmdet"
|
| 172 |
+
if local_mmdet_pkg.exists():
|
| 173 |
+
sys.path.insert(0, str(local_mmdet_root))
|
| 174 |
+
from mmdet.registry import DATASETS # type: ignore
|
| 175 |
+
return DATASETS
|
| 176 |
+
raise
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def parse_args():
|
| 180 |
+
parser = argparse.ArgumentParser(
|
| 181 |
+
description=(
|
| 182 |
+
"Run Grounding DINO predictions with Rex-Omni evaluation logic "
|
| 183 |
+
"(large/small object IoU split)."
|
| 184 |
+
)
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument("--config", required=True, help="MMDetection config path")
|
| 187 |
+
parser.add_argument("--pkl", required=True, help="MMDetection test output pkl")
|
| 188 |
+
parser.add_argument(
|
| 189 |
+
"--output-jsonl",
|
| 190 |
+
default=None,
|
| 191 |
+
help="Converted jsonl for Rex evaluation (default: <pkl>_rex_eval.jsonl)",
|
| 192 |
+
)
|
| 193 |
+
parser.add_argument(
|
| 194 |
+
"--output-report",
|
| 195 |
+
default=None,
|
| 196 |
+
help="Rex-style txt report path (default: <output-jsonl>_results.txt)",
|
| 197 |
+
)
|
| 198 |
+
parser.add_argument(
|
| 199 |
+
"--rex-eval-script",
|
| 200 |
+
default=DEFAULT_REX_EVAL_SCRIPT,
|
| 201 |
+
help="Path to Rex-Omni evaluation/evaluate.py",
|
| 202 |
+
)
|
| 203 |
+
parser.add_argument(
|
| 204 |
+
"--score-thr",
|
| 205 |
+
type=float,
|
| 206 |
+
default=0.3,
|
| 207 |
+
help="Prediction score threshold before Rex evaluation",
|
| 208 |
+
)
|
| 209 |
+
parser.add_argument(
|
| 210 |
+
"--large-iou-thr",
|
| 211 |
+
type=float,
|
| 212 |
+
default=0.5,
|
| 213 |
+
help="IoU threshold for large objects in Rex evaluation",
|
| 214 |
+
)
|
| 215 |
+
parser.add_argument(
|
| 216 |
+
"--small-iou-thr",
|
| 217 |
+
type=float,
|
| 218 |
+
default=0.2,
|
| 219 |
+
help="IoU threshold for small objects in Rex evaluation",
|
| 220 |
+
)
|
| 221 |
+
parser.add_argument(
|
| 222 |
+
"--size-thr",
|
| 223 |
+
type=int,
|
| 224 |
+
default=50,
|
| 225 |
+
help="Size threshold to split large/small objects in Rex evaluation",
|
| 226 |
+
)
|
| 227 |
+
return parser.parse_args()
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def main():
|
| 231 |
+
args = parse_args()
|
| 232 |
+
|
| 233 |
+
output_jsonl = args.output_jsonl
|
| 234 |
+
if output_jsonl is None:
|
| 235 |
+
pkl_path = Path(args.pkl)
|
| 236 |
+
output_jsonl = str(pkl_path.with_suffix("")) + "_rex_eval.jsonl"
|
| 237 |
+
|
| 238 |
+
output_report = args.output_report
|
| 239 |
+
if output_report is None:
|
| 240 |
+
if output_jsonl.endswith(".jsonl"):
|
| 241 |
+
output_report = output_jsonl[:-6] + "_results.txt"
|
| 242 |
+
else:
|
| 243 |
+
output_report = output_jsonl + "_results.txt"
|
| 244 |
+
|
| 245 |
+
output_jsonl_dir = os.path.dirname(output_jsonl)
|
| 246 |
+
output_report_dir = os.path.dirname(output_report)
|
| 247 |
+
if output_jsonl_dir:
|
| 248 |
+
os.makedirs(output_jsonl_dir, exist_ok=True)
|
| 249 |
+
if output_report_dir:
|
| 250 |
+
os.makedirs(output_report_dir, exist_ok=True)
|
| 251 |
+
|
| 252 |
+
print(f"[Info] Loading config: {args.config}")
|
| 253 |
+
cfg = Config.fromfile(args.config)
|
| 254 |
+
init_default_scope(cfg.get("default_scope", "mmdet"))
|
| 255 |
+
DATASETS = _load_datasets_registry()
|
| 256 |
+
|
| 257 |
+
print("[Info] Building test dataset...")
|
| 258 |
+
dataset = DATASETS.build(cfg.test_dataloader.dataset)
|
| 259 |
+
class_names = dataset.metainfo["classes"]
|
| 260 |
+
print(f"[Info] Classes ({len(class_names)}): {class_names}")
|
| 261 |
+
|
| 262 |
+
print(f"[Info] Loading predictions: {args.pkl}")
|
| 263 |
+
predictions = mmengine.load(args.pkl)
|
| 264 |
+
|
| 265 |
+
print("[Info] Converting predictions to Rex jsonl format...")
|
| 266 |
+
rows = _build_eval_rows(dataset, predictions, class_names, args.score_thr)
|
| 267 |
+
|
| 268 |
+
with open(output_jsonl, "w", encoding="utf-8") as f:
|
| 269 |
+
for row in rows:
|
| 270 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 271 |
+
|
| 272 |
+
print(f"[Info] Converted jsonl saved to: {output_jsonl}")
|
| 273 |
+
print(f"[Info] Number of samples: {len(rows)}")
|
| 274 |
+
|
| 275 |
+
evaluate_jsonl = _load_rex_evaluate_fn(args.rex_eval_script)
|
| 276 |
+
print(f"[Info] Running Rex evaluate.py method from: {args.rex_eval_script}")
|
| 277 |
+
evaluate_jsonl(
|
| 278 |
+
output_jsonl,
|
| 279 |
+
large_iou_threshold=args.large_iou_thr,
|
| 280 |
+
small_iou_threshold=args.small_iou_thr,
|
| 281 |
+
size_threshold=args.size_thr,
|
| 282 |
+
output_file=output_report,
|
| 283 |
+
)
|
| 284 |
+
print(f"[Info] Rex-style report saved to: {output_report}")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
if __name__ == "__main__":
|
| 288 |
+
main()
|
grounding-dino/inference_crop_grounding_dino.py
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run Grounding DINO on crop regions defined in a jsonl file.
|
| 3 |
+
|
| 4 |
+
This script mirrors the crop-based inference flow used by
|
| 5 |
+
`Rex-Omni_bxd/evaluation/inference_text_prompt_deny_crop.py`:
|
| 6 |
+
1. Read per-image crop boxes from `extracted_predictions[crop_key]`.
|
| 7 |
+
2. Run Grounding DINO on each crop region.
|
| 8 |
+
3. Map crop-local detections back to the original image coordinate system.
|
| 9 |
+
4. Optionally filter duplicate boxes across crops by IoU.
|
| 10 |
+
5. Save jsonl rows that keep the original fields and append crop detections.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import math
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
from copy import deepcopy
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
| 22 |
+
|
| 23 |
+
import cv2
|
| 24 |
+
from tqdm import tqdm
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def patch_torch_load() -> None:
|
| 28 |
+
"""Work around PyTorch 2.6+ weights_only default during checkpoint load."""
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
original_torch_load = torch.load
|
| 32 |
+
|
| 33 |
+
def patched_torch_load(*args, **kwargs):
|
| 34 |
+
if 'weights_only' not in kwargs:
|
| 35 |
+
kwargs['weights_only'] = False
|
| 36 |
+
return original_torch_load(*args, **kwargs)
|
| 37 |
+
|
| 38 |
+
torch.load = patched_torch_load
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def ensure_local_mmdet(mmdet_root: Path) -> None:
|
| 42 |
+
if str(mmdet_root) not in sys.path:
|
| 43 |
+
sys.path.insert(0, str(mmdet_root))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def parse_args() -> argparse.Namespace:
|
| 47 |
+
base_dir = Path(__file__).resolve().parent
|
| 48 |
+
work_dir = base_dir / 'work_dirs' / 'mm_grounding_dino_traffic'
|
| 49 |
+
|
| 50 |
+
parser = argparse.ArgumentParser(
|
| 51 |
+
description='Grounding DINO crop-based inference on a jsonl dataset.')
|
| 52 |
+
parser.add_argument(
|
| 53 |
+
'--config',
|
| 54 |
+
default=str(work_dir / 'grounding_dino_swin-t_finetune_traffic.py'),
|
| 55 |
+
help='Grounding DINO config path.')
|
| 56 |
+
parser.add_argument(
|
| 57 |
+
'--checkpoint',
|
| 58 |
+
default='',
|
| 59 |
+
help='Checkpoint path. If empty, resolve from work_dir automatically.')
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
'--test-jsonl-path',
|
| 62 |
+
default=str(
|
| 63 |
+
base_dir.parent.parent
|
| 64 |
+
/ 'rex_data'
|
| 65 |
+
/ 'data'
|
| 66 |
+
/ 'filtered_low_precision_lt0.5_removed'
|
| 67 |
+
/ '50_裁剪'
|
| 68 |
+
/ 'answer.jsonl'
|
| 69 |
+
),
|
| 70 |
+
help='Input jsonl with crop proposals.')
|
| 71 |
+
parser.add_argument(
|
| 72 |
+
'--image-root-dir',
|
| 73 |
+
default='',
|
| 74 |
+
help='Prefix for relative image paths. Absolute paths are used as-is.')
|
| 75 |
+
parser.add_argument(
|
| 76 |
+
'--save-path',
|
| 77 |
+
default=str(base_dir / 'eval_output' / 'crop_grounding_dino.jsonl'),
|
| 78 |
+
help='Output jsonl path.')
|
| 79 |
+
parser.add_argument(
|
| 80 |
+
'--crop-key',
|
| 81 |
+
default='crop',
|
| 82 |
+
help='Key inside extracted_predictions that stores crop boxes.')
|
| 83 |
+
parser.add_argument(
|
| 84 |
+
'--crop-expand',
|
| 85 |
+
type=int,
|
| 86 |
+
default=50,
|
| 87 |
+
help='Expand each crop by N pixels on all sides.')
|
| 88 |
+
parser.add_argument(
|
| 89 |
+
'--score-thr',
|
| 90 |
+
type=float,
|
| 91 |
+
default=0.7,
|
| 92 |
+
help='Grounding DINO score threshold.')
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
'--iou-thr',
|
| 95 |
+
type=float,
|
| 96 |
+
default=0.5,
|
| 97 |
+
help='IoU threshold used to suppress duplicates across crops.')
|
| 98 |
+
parser.add_argument(
|
| 99 |
+
'--boundary-tolerance',
|
| 100 |
+
type=float,
|
| 101 |
+
default=-1.0,
|
| 102 |
+
help='Discard boxes touching crop boundary when >= 0; disable when < 0.')
|
| 103 |
+
parser.add_argument(
|
| 104 |
+
'--device',
|
| 105 |
+
default='cuda:0',
|
| 106 |
+
help='Inference device, e.g. cuda:0 or cpu.')
|
| 107 |
+
parser.add_argument(
|
| 108 |
+
'--start-idx',
|
| 109 |
+
type=int,
|
| 110 |
+
default=0,
|
| 111 |
+
help='Start index in jsonl.')
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
'--end-idx',
|
| 114 |
+
type=int,
|
| 115 |
+
default=-1,
|
| 116 |
+
help='End index in jsonl, -1 means all.')
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
'--texts',
|
| 119 |
+
default='',
|
| 120 |
+
help=(
|
| 121 |
+
'Custom text prompt entities. Example: '
|
| 122 |
+
'"traffic sign . street light . bollard ." '
|
| 123 |
+
'If empty, use config metainfo classes.'
|
| 124 |
+
))
|
| 125 |
+
parser.add_argument(
|
| 126 |
+
'--mmdet-root',
|
| 127 |
+
default=str(base_dir / 'mmdetection'),
|
| 128 |
+
help='Local mmdetection repo root.')
|
| 129 |
+
return parser.parse_args()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def resolve_checkpoint(requested_path: str, config_path: Path) -> Path:
|
| 133 |
+
if requested_path:
|
| 134 |
+
checkpoint = Path(requested_path)
|
| 135 |
+
if checkpoint.is_file():
|
| 136 |
+
return checkpoint
|
| 137 |
+
raise FileNotFoundError(f'Checkpoint not found: {checkpoint}')
|
| 138 |
+
|
| 139 |
+
work_dir = config_path.parent
|
| 140 |
+
best_paths = sorted(work_dir.glob('best*.pth'))
|
| 141 |
+
if best_paths:
|
| 142 |
+
return best_paths[-1]
|
| 143 |
+
|
| 144 |
+
last_checkpoint = work_dir / 'last_checkpoint'
|
| 145 |
+
if last_checkpoint.is_file():
|
| 146 |
+
path = Path(last_checkpoint.read_text(encoding='utf-8').strip())
|
| 147 |
+
if path.is_file():
|
| 148 |
+
return path
|
| 149 |
+
|
| 150 |
+
all_paths = sorted(work_dir.glob('*.pth'))
|
| 151 |
+
if all_paths:
|
| 152 |
+
return all_paths[-1]
|
| 153 |
+
|
| 154 |
+
raise FileNotFoundError(
|
| 155 |
+
f'No checkpoint found under work dir: {work_dir}')
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def load_jsonl(path: str) -> List[dict]:
|
| 159 |
+
rows = []
|
| 160 |
+
with open(path, 'r', encoding='utf-8') as f:
|
| 161 |
+
for line in f:
|
| 162 |
+
line = line.strip()
|
| 163 |
+
if not line:
|
| 164 |
+
continue
|
| 165 |
+
rows.append(json.loads(line))
|
| 166 |
+
return rows
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def resolve_image_path(image_path: str, image_root_dir: str) -> str:
|
| 170 |
+
if not image_root_dir or os.path.isabs(image_path):
|
| 171 |
+
return image_path
|
| 172 |
+
return os.path.join(image_root_dir, image_path)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def get_crop_boxes(extracted_predictions, crop_key: str) -> List[list]:
|
| 176 |
+
if not extracted_predictions:
|
| 177 |
+
return []
|
| 178 |
+
if isinstance(extracted_predictions, dict):
|
| 179 |
+
return extracted_predictions.get(crop_key, []) or []
|
| 180 |
+
if isinstance(extracted_predictions, list):
|
| 181 |
+
return extracted_predictions
|
| 182 |
+
return []
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def clamp_crop_box(
|
| 186 |
+
box: Sequence[float],
|
| 187 |
+
image_w: int,
|
| 188 |
+
image_h: int,
|
| 189 |
+
expand: int = 0,
|
| 190 |
+
) -> Optional[List[int]]:
|
| 191 |
+
if not isinstance(box, (list, tuple)) or len(box) < 4:
|
| 192 |
+
return None
|
| 193 |
+
try:
|
| 194 |
+
x0, y0, x1, y1 = [float(v) for v in box[:4]]
|
| 195 |
+
except (TypeError, ValueError):
|
| 196 |
+
return None
|
| 197 |
+
|
| 198 |
+
expand = max(0, int(expand))
|
| 199 |
+
x0_i = max(0, int(math.floor(x0)) - expand)
|
| 200 |
+
y0_i = max(0, int(math.floor(y0)) - expand)
|
| 201 |
+
x1_i = min(image_w, int(math.ceil(x1)) + expand)
|
| 202 |
+
y1_i = min(image_h, int(math.ceil(y1)) + expand)
|
| 203 |
+
|
| 204 |
+
if x1_i <= x0_i or y1_i <= y0_i:
|
| 205 |
+
return None
|
| 206 |
+
return [x0_i, y0_i, x1_i, y1_i]
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def is_box_touching_boundary(
|
| 210 |
+
box: Sequence[float],
|
| 211 |
+
crop_w: int,
|
| 212 |
+
crop_h: int,
|
| 213 |
+
tolerance: float,
|
| 214 |
+
) -> bool:
|
| 215 |
+
if tolerance < 0 or len(box) < 4:
|
| 216 |
+
return False
|
| 217 |
+
x0, y0, x1, y1 = box[:4]
|
| 218 |
+
return (
|
| 219 |
+
x0 <= tolerance
|
| 220 |
+
or y0 <= tolerance
|
| 221 |
+
or x1 >= crop_w - tolerance
|
| 222 |
+
or y1 >= crop_h - tolerance
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def calculate_iou(box1: Sequence[float], box2: Sequence[float]) -> float:
|
| 227 |
+
if len(box1) < 4 or len(box2) < 4:
|
| 228 |
+
return 0.0
|
| 229 |
+
|
| 230 |
+
x0 = max(box1[0], box2[0])
|
| 231 |
+
y0 = max(box1[1], box2[1])
|
| 232 |
+
x1 = min(box1[2], box2[2])
|
| 233 |
+
y1 = min(box1[3], box2[3])
|
| 234 |
+
if x1 <= x0 or y1 <= y0:
|
| 235 |
+
return 0.0
|
| 236 |
+
|
| 237 |
+
inter = (x1 - x0) * (y1 - y0)
|
| 238 |
+
area1 = max(0.0, box1[2] - box1[0]) * max(0.0, box1[3] - box1[1])
|
| 239 |
+
area2 = max(0.0, box2[2] - box2[0]) * max(0.0, box2[3] - box2[1])
|
| 240 |
+
union = area1 + area2 - inter
|
| 241 |
+
if union <= 0:
|
| 242 |
+
return 0.0
|
| 243 |
+
return inter / union
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def has_overlap_with_existing(
|
| 247 |
+
new_box: Sequence[float],
|
| 248 |
+
existing_boxes: Iterable[Sequence[float]],
|
| 249 |
+
iou_threshold: float,
|
| 250 |
+
) -> bool:
|
| 251 |
+
return any(calculate_iou(new_box, box) > iou_threshold for box in existing_boxes)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def normalize_entity_name(name: str) -> str:
|
| 255 |
+
return name.strip()
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def parse_text_entities(texts: str) -> List[str]:
|
| 259 |
+
entities = []
|
| 260 |
+
for item in texts.split('.'):
|
| 261 |
+
item = normalize_entity_name(item)
|
| 262 |
+
if item:
|
| 263 |
+
entities.append(item)
|
| 264 |
+
return entities
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def flatten_config_classes(cfg) -> List[str]:
|
| 268 |
+
classes = cfg.get('metainfo', {}).get('classes')
|
| 269 |
+
if classes:
|
| 270 |
+
return [str(x) for x in classes]
|
| 271 |
+
classes = cfg.get('class_name')
|
| 272 |
+
if classes:
|
| 273 |
+
return [str(x) for x in classes]
|
| 274 |
+
raise ValueError('Cannot find classes from config metainfo/class_name.')
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def group_predictions_by_label(
|
| 278 |
+
data_sample,
|
| 279 |
+
fallback_entities: Optional[Sequence[str]] = None,
|
| 280 |
+
) -> Dict[str, List[List[float]]]:
|
| 281 |
+
grouped = defaultdict(list)
|
| 282 |
+
pred_instances = data_sample.pred_instances
|
| 283 |
+
bboxes = pred_instances.bboxes.detach().cpu().numpy()
|
| 284 |
+
label_names = list(getattr(pred_instances, 'label_names', []))
|
| 285 |
+
labels = []
|
| 286 |
+
if hasattr(pred_instances, 'labels'):
|
| 287 |
+
labels = pred_instances.labels.detach().cpu().tolist()
|
| 288 |
+
|
| 289 |
+
if not label_names and fallback_entities is not None:
|
| 290 |
+
for label in labels:
|
| 291 |
+
label = int(label)
|
| 292 |
+
if 0 <= label < len(fallback_entities):
|
| 293 |
+
label_names.append(str(fallback_entities[label]))
|
| 294 |
+
else:
|
| 295 |
+
label_names.append(str(label))
|
| 296 |
+
|
| 297 |
+
for bbox, label_name in zip(bboxes, label_names):
|
| 298 |
+
grouped[str(label_name)].append([float(v) for v in bbox.tolist()])
|
| 299 |
+
return dict(grouped)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def adjust_predictions_to_global(
|
| 303 |
+
predictions: Dict[str, List[List[float]]],
|
| 304 |
+
offset_x: int,
|
| 305 |
+
offset_y: int,
|
| 306 |
+
) -> Dict[str, List[List[float]]]:
|
| 307 |
+
adjusted = {}
|
| 308 |
+
for category, boxes in predictions.items():
|
| 309 |
+
adjusted[category] = []
|
| 310 |
+
for box in boxes:
|
| 311 |
+
if len(box) < 4:
|
| 312 |
+
continue
|
| 313 |
+
adjusted[category].append([
|
| 314 |
+
box[0] + offset_x,
|
| 315 |
+
box[1] + offset_y,
|
| 316 |
+
box[2] + offset_x,
|
| 317 |
+
box[3] + offset_y,
|
| 318 |
+
])
|
| 319 |
+
return adjusted
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def filter_local_predictions(
|
| 323 |
+
predictions: Dict[str, List[List[float]]],
|
| 324 |
+
crop_w: int,
|
| 325 |
+
crop_h: int,
|
| 326 |
+
boundary_tolerance: float,
|
| 327 |
+
) -> Dict[str, List[List[float]]]:
|
| 328 |
+
filtered = {}
|
| 329 |
+
for category, boxes in predictions.items():
|
| 330 |
+
keep = []
|
| 331 |
+
for box in boxes:
|
| 332 |
+
if is_box_touching_boundary(box, crop_w, crop_h, boundary_tolerance):
|
| 333 |
+
continue
|
| 334 |
+
keep.append(box)
|
| 335 |
+
filtered[category] = keep
|
| 336 |
+
return filtered
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def filter_global_predictions(
|
| 340 |
+
predictions: Dict[str, List[List[float]]],
|
| 341 |
+
existing_boxes_by_category: Dict[str, List[List[float]]],
|
| 342 |
+
iou_threshold: float,
|
| 343 |
+
) -> Tuple[Dict[str, List[List[float]]], Dict[str, List[List[float]]]]:
|
| 344 |
+
filtered = {}
|
| 345 |
+
updated_existing = {
|
| 346 |
+
key: [list(box) for box in value]
|
| 347 |
+
for key, value in existing_boxes_by_category.items()
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
for category, boxes in predictions.items():
|
| 351 |
+
updated_existing.setdefault(category, [])
|
| 352 |
+
keep = []
|
| 353 |
+
for box in boxes:
|
| 354 |
+
if has_overlap_with_existing(box, updated_existing[category], iou_threshold):
|
| 355 |
+
continue
|
| 356 |
+
keep.append(box)
|
| 357 |
+
updated_existing[category].append(box)
|
| 358 |
+
filtered[category] = keep
|
| 359 |
+
|
| 360 |
+
return filtered, updated_existing
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def merge_prediction_dicts(dicts: Iterable[Dict[str, List[List[float]]]]) -> Dict[str, List[List[float]]]:
|
| 364 |
+
merged = defaultdict(list)
|
| 365 |
+
for pred in dicts:
|
| 366 |
+
for category, boxes in pred.items():
|
| 367 |
+
merged[category].extend(boxes)
|
| 368 |
+
return dict(merged)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def main() -> None:
|
| 372 |
+
args = parse_args()
|
| 373 |
+
patch_torch_load()
|
| 374 |
+
|
| 375 |
+
config_path = Path(args.config).resolve()
|
| 376 |
+
checkpoint_path = resolve_checkpoint(args.checkpoint, config_path)
|
| 377 |
+
mmdet_root = Path(args.mmdet_root).resolve()
|
| 378 |
+
|
| 379 |
+
ensure_local_mmdet(mmdet_root)
|
| 380 |
+
|
| 381 |
+
from mmengine.config import Config
|
| 382 |
+
from mmengine.registry import init_default_scope
|
| 383 |
+
from mmdet.apis import inference_detector, init_detector
|
| 384 |
+
|
| 385 |
+
if args.crop_expand < 0:
|
| 386 |
+
raise ValueError('--crop_expand must be >= 0')
|
| 387 |
+
if args.end_idx != -1 and args.end_idx < args.start_idx:
|
| 388 |
+
raise ValueError('--end_idx must be -1 or >= --start_idx')
|
| 389 |
+
|
| 390 |
+
save_dir = os.path.dirname(args.save_path)
|
| 391 |
+
if save_dir:
|
| 392 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 393 |
+
|
| 394 |
+
print(f'[Info] Loading config: {config_path}')
|
| 395 |
+
cfg = Config.fromfile(str(config_path))
|
| 396 |
+
init_default_scope(cfg.get('default_scope', 'mmdet'))
|
| 397 |
+
|
| 398 |
+
entities = parse_text_entities(args.texts) if args.texts else flatten_config_classes(cfg)
|
| 399 |
+
print(f'[Info] Using {len(entities)} entities: {entities}')
|
| 400 |
+
|
| 401 |
+
print(f'[Info] Loading checkpoint: {checkpoint_path}')
|
| 402 |
+
model = init_detector(str(config_path), str(checkpoint_path), device=args.device)
|
| 403 |
+
|
| 404 |
+
prompt_entities: Sequence[str] = tuple(entities)
|
| 405 |
+
|
| 406 |
+
print(f'[Info] Loading jsonl: {args.test_jsonl_path}')
|
| 407 |
+
rows = load_jsonl(args.test_jsonl_path)
|
| 408 |
+
if args.end_idx == -1:
|
| 409 |
+
selected_rows = rows[args.start_idx:]
|
| 410 |
+
else:
|
| 411 |
+
selected_rows = rows[args.start_idx:args.end_idx]
|
| 412 |
+
print(f'[Info] Processing {len(selected_rows)} rows')
|
| 413 |
+
|
| 414 |
+
predictions = []
|
| 415 |
+
for entry in tqdm(selected_rows, desc='Grounding DINO crop inference'):
|
| 416 |
+
image_path = entry.get('image_path', '')
|
| 417 |
+
extracted_predictions = entry.get('extracted_predictions', {})
|
| 418 |
+
crop_boxes = get_crop_boxes(extracted_predictions, args.crop_key)
|
| 419 |
+
if not crop_boxes:
|
| 420 |
+
continue
|
| 421 |
+
|
| 422 |
+
full_image_path = resolve_image_path(image_path, args.image_root_dir)
|
| 423 |
+
if not os.path.exists(full_image_path):
|
| 424 |
+
print(f'[Warn] Image not found: {full_image_path}')
|
| 425 |
+
continue
|
| 426 |
+
|
| 427 |
+
image = cv2.imread(full_image_path)
|
| 428 |
+
if image is None:
|
| 429 |
+
print(f'[Warn] Failed to read image: {full_image_path}')
|
| 430 |
+
continue
|
| 431 |
+
image_h, image_w = image.shape[:2]
|
| 432 |
+
|
| 433 |
+
crop_outputs = []
|
| 434 |
+
merged_outputs = []
|
| 435 |
+
existing_boxes_by_category: Dict[str, List[List[float]]] = {}
|
| 436 |
+
|
| 437 |
+
for crop_idx, crop_box in enumerate(crop_boxes):
|
| 438 |
+
crop_box_int = clamp_crop_box(
|
| 439 |
+
crop_box, image_w, image_h, expand=args.crop_expand)
|
| 440 |
+
if crop_box_int is None:
|
| 441 |
+
print(f'[Warn] Skip invalid crop box #{crop_idx}: {crop_box}')
|
| 442 |
+
continue
|
| 443 |
+
|
| 444 |
+
x0, y0, x1, y1 = crop_box_int
|
| 445 |
+
crop_img = image[y0:y1, x0:x1]
|
| 446 |
+
crop_h, crop_w = crop_img.shape[:2]
|
| 447 |
+
if crop_h == 0 or crop_w == 0:
|
| 448 |
+
continue
|
| 449 |
+
|
| 450 |
+
result = inference_detector(
|
| 451 |
+
model,
|
| 452 |
+
crop_img,
|
| 453 |
+
text_prompt=prompt_entities,
|
| 454 |
+
custom_entities=True,
|
| 455 |
+
)
|
| 456 |
+
pred_instances = result.pred_instances
|
| 457 |
+
if hasattr(pred_instances, 'scores'):
|
| 458 |
+
keep = pred_instances.scores > args.score_thr
|
| 459 |
+
pred_instances = pred_instances[keep]
|
| 460 |
+
result.pred_instances = pred_instances
|
| 461 |
+
|
| 462 |
+
local_predictions = group_predictions_by_label(
|
| 463 |
+
result, fallback_entities=prompt_entities)
|
| 464 |
+
filtered_local = filter_local_predictions(
|
| 465 |
+
local_predictions,
|
| 466 |
+
crop_w=crop_w,
|
| 467 |
+
crop_h=crop_h,
|
| 468 |
+
boundary_tolerance=args.boundary_tolerance,
|
| 469 |
+
)
|
| 470 |
+
global_predictions = adjust_predictions_to_global(
|
| 471 |
+
filtered_local, x0, y0)
|
| 472 |
+
filtered_global, existing_boxes_by_category = filter_global_predictions(
|
| 473 |
+
global_predictions,
|
| 474 |
+
existing_boxes_by_category=existing_boxes_by_category,
|
| 475 |
+
iou_threshold=args.iou_thr,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
crop_outputs.append(
|
| 479 |
+
{
|
| 480 |
+
'crop_idx': crop_idx,
|
| 481 |
+
'crop_box': crop_box_int,
|
| 482 |
+
'local_predictions': filtered_local,
|
| 483 |
+
'global_predictions': filtered_global,
|
| 484 |
+
})
|
| 485 |
+
merged_outputs.append(filtered_global)
|
| 486 |
+
|
| 487 |
+
if not crop_outputs:
|
| 488 |
+
continue
|
| 489 |
+
|
| 490 |
+
prediction_row = deepcopy(entry)
|
| 491 |
+
prediction_row['text_prompt_entities'] = list(prompt_entities)
|
| 492 |
+
prediction_row['new_extract'] = merged_outputs
|
| 493 |
+
prediction_row['crop_predictions'] = crop_outputs
|
| 494 |
+
prediction_row['merged_predictions'] = merge_prediction_dicts(merged_outputs)
|
| 495 |
+
predictions.append(prediction_row)
|
| 496 |
+
|
| 497 |
+
print(f'[Info] Saving {len(predictions)} rows to: {args.save_path}')
|
| 498 |
+
with open(args.save_path, 'w', encoding='utf-8') as f:
|
| 499 |
+
for row in predictions:
|
| 500 |
+
f.write(json.dumps(row, ensure_ascii=False) + '\n')
|
| 501 |
+
|
| 502 |
+
print('[Info] Done.')
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
if __name__ == '__main__':
|
| 506 |
+
main()
|
grounding-dino/run_eval_and_vis.sh
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# ================================================================
|
| 3 |
+
# Grounding DINO 评估 + 可视化 一体化脚本
|
| 4 |
+
# 功能:
|
| 5 |
+
# 1. 用 test.py 跑推理,保存 pkl 结果 + 可视化图片
|
| 6 |
+
# 2. 用自定义脚本计算 Precision / Recall / F1 (per-class + overall)
|
| 7 |
+
# 3. 用 analyze_results.py 展示 topk 好/坏样本
|
| 8 |
+
# 4. 用 confusion_matrix.py 生成混淆矩阵
|
| 9 |
+
# ================================================================
|
| 10 |
+
set -euo pipefail
|
| 11 |
+
|
| 12 |
+
resolve_python() {
|
| 13 |
+
if [ -n "${PYTHON:-}" ]; then
|
| 14 |
+
echo "${PYTHON}"
|
| 15 |
+
elif command -v python3 >/dev/null 2>&1; then
|
| 16 |
+
command -v python3
|
| 17 |
+
elif command -v python >/dev/null 2>&1; then
|
| 18 |
+
command -v python
|
| 19 |
+
else
|
| 20 |
+
echo ""
|
| 21 |
+
fi
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
detect_gpus() {
|
| 25 |
+
if [ -n "${GPUS:-}" ]; then
|
| 26 |
+
echo "${GPUS}"
|
| 27 |
+
return
|
| 28 |
+
fi
|
| 29 |
+
|
| 30 |
+
if [ -n "${CUDA_VISIBLE_DEVICES:-}" ]; then
|
| 31 |
+
awk -F',' '{print NF}' <<< "${CUDA_VISIBLE_DEVICES}"
|
| 32 |
+
return
|
| 33 |
+
fi
|
| 34 |
+
|
| 35 |
+
if command -v nvidia-smi >/dev/null 2>&1; then
|
| 36 |
+
local n
|
| 37 |
+
n=$(nvidia-smi -L 2>/dev/null | wc -l | tr -d ' ')
|
| 38 |
+
if [ "${n}" -gt 0 ]; then
|
| 39 |
+
echo "${n}"
|
| 40 |
+
return
|
| 41 |
+
fi
|
| 42 |
+
fi
|
| 43 |
+
|
| 44 |
+
echo 1
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
resolve_checkpoint() {
|
| 48 |
+
local requested_path="${1:-}"
|
| 49 |
+
local work_dir="${2}"
|
| 50 |
+
local best_checkpoint
|
| 51 |
+
|
| 52 |
+
if [ -n "${requested_path}" ] && [ -f "${requested_path}" ]; then
|
| 53 |
+
echo "${requested_path}"
|
| 54 |
+
return
|
| 55 |
+
fi
|
| 56 |
+
|
| 57 |
+
best_checkpoint=$(find "${work_dir}" -maxdepth 1 -type f -name 'best*.pth' | sort | tail -n 1)
|
| 58 |
+
if [ -n "${best_checkpoint}" ] && [ -f "${best_checkpoint}" ]; then
|
| 59 |
+
echo "${best_checkpoint}"
|
| 60 |
+
return
|
| 61 |
+
fi
|
| 62 |
+
|
| 63 |
+
if [ -f "${work_dir}/last_checkpoint" ]; then
|
| 64 |
+
local last_checkpoint
|
| 65 |
+
last_checkpoint=$(cat "${work_dir}/last_checkpoint")
|
| 66 |
+
if [ -f "${last_checkpoint}" ]; then
|
| 67 |
+
echo "${last_checkpoint}"
|
| 68 |
+
return
|
| 69 |
+
fi
|
| 70 |
+
fi
|
| 71 |
+
|
| 72 |
+
local latest_checkpoint
|
| 73 |
+
latest_checkpoint=$(find "${work_dir}" -maxdepth 1 -type f -name '*.pth' | sort | tail -n 1)
|
| 74 |
+
if [ -n "${latest_checkpoint}" ] && [ -f "${latest_checkpoint}" ]; then
|
| 75 |
+
echo "${latest_checkpoint}"
|
| 76 |
+
return
|
| 77 |
+
fi
|
| 78 |
+
|
| 79 |
+
echo ""
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
# ============== 路径配置 ==============
|
| 83 |
+
PYTHON="$(resolve_python)"
|
| 84 |
+
BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 85 |
+
MMDET_DIR="${BASE_DIR}/mmdetection"
|
| 86 |
+
WORK_DIR="${BASE_DIR}/work_dirs/mm_grounding_dino_traffic"
|
| 87 |
+
|
| 88 |
+
CONFIG="${CONFIG:-${WORK_DIR}/grounding_dino_swin-t_finetune_traffic.py}"
|
| 89 |
+
CHECKPOINT="${CHECKPOINT:-${WORK_DIR}/best_coco_traffic_sign_precision_epoch_18.pth}"
|
| 90 |
+
CHECKPOINT="$(resolve_checkpoint "${CHECKPOINT}" "${WORK_DIR}")"
|
| 91 |
+
|
| 92 |
+
OUTPUT_DIR="${OUTPUT_DIR:-${BASE_DIR}/eval_output}"
|
| 93 |
+
PKL_FILE="${OUTPUT_DIR}/predictions.pkl"
|
| 94 |
+
VIS_DIR="${OUTPUT_DIR}/vis_images"
|
| 95 |
+
ANALYZE_DIR="${OUTPUT_DIR}/analyze_results"
|
| 96 |
+
CM_DIR="${OUTPUT_DIR}/confusion_matrix"
|
| 97 |
+
|
| 98 |
+
SCORE_THR="${SCORE_THR:-0.3}"
|
| 99 |
+
TOPK="${TOPK:-20}"
|
| 100 |
+
GPUS="$(detect_gpus)"
|
| 101 |
+
BATCH_SIZE="${BATCH_SIZE:-4}"
|
| 102 |
+
|
| 103 |
+
if [ -z "${PYTHON}" ]; then
|
| 104 |
+
echo "Error: python executable not found."
|
| 105 |
+
exit 1
|
| 106 |
+
fi
|
| 107 |
+
|
| 108 |
+
if [ ! -f "${CONFIG}" ]; then
|
| 109 |
+
echo "Error: config file not found: ${CONFIG}"
|
| 110 |
+
exit 1
|
| 111 |
+
fi
|
| 112 |
+
|
| 113 |
+
if [ -z "${CHECKPOINT}" ] || [ ! -f "${CHECKPOINT}" ]; then
|
| 114 |
+
echo "Error: checkpoint file not found."
|
| 115 |
+
echo "Tried default path and fallback lookup under: ${WORK_DIR}"
|
| 116 |
+
exit 1
|
| 117 |
+
fi
|
| 118 |
+
|
| 119 |
+
mkdir -p "$OUTPUT_DIR" "$VIS_DIR" "$ANALYZE_DIR" "$CM_DIR"
|
| 120 |
+
|
| 121 |
+
# ============== Step 1: 推理 + 保存pkl + 可视化 ==============
|
| 122 |
+
echo "========================================"
|
| 123 |
+
echo "STEP 1: 运行推理 (保存pkl + 可视化)"
|
| 124 |
+
echo "========================================"
|
| 125 |
+
echo "CONFIG: ${CONFIG}"
|
| 126 |
+
echo "CHECKPOINT: ${CHECKPOINT}"
|
| 127 |
+
echo "GPUS: ${GPUS}"
|
| 128 |
+
echo "BATCH_SIZE: ${BATCH_SIZE}"
|
| 129 |
+
|
| 130 |
+
cd "${MMDET_DIR}"
|
| 131 |
+
if [ "${GPUS}" -le 1 ]; then
|
| 132 |
+
"${PYTHON}" tools/test.py \
|
| 133 |
+
"$CONFIG" \
|
| 134 |
+
"$CHECKPOINT" \
|
| 135 |
+
--out "$PKL_FILE" \
|
| 136 |
+
--show-dir "$VIS_DIR" \
|
| 137 |
+
--cfg-options test_dataloader.batch_size="${BATCH_SIZE}"
|
| 138 |
+
else
|
| 139 |
+
bash tools/dist_test.sh \
|
| 140 |
+
"$CONFIG" \
|
| 141 |
+
"$CHECKPOINT" \
|
| 142 |
+
"${GPUS}" \
|
| 143 |
+
--out "$PKL_FILE" \
|
| 144 |
+
--show-dir "$VIS_DIR" \
|
| 145 |
+
--cfg-options test_dataloader.batch_size="${BATCH_SIZE}"
|
| 146 |
+
fi
|
| 147 |
+
|
| 148 |
+
echo ">>> pkl 结果已保存到: $PKL_FILE"
|
| 149 |
+
echo ">>> 可视化结果已保存到: $VIS_DIR"
|
| 150 |
+
|
| 151 |
+
# ============== Step 2: 计算 Precision / Recall / F1 ==============
|
| 152 |
+
echo "========================================"
|
| 153 |
+
echo "STEP 2: 计算 Precision / Recall / F1"
|
| 154 |
+
echo "========================================"
|
| 155 |
+
|
| 156 |
+
"${PYTHON}" ${BASE_DIR}/compute_recall_f1.py \
|
| 157 |
+
--config "$CONFIG" \
|
| 158 |
+
--pkl "$PKL_FILE" \
|
| 159 |
+
--score-thr $SCORE_THR \
|
| 160 |
+
--output "${OUTPUT_DIR}/metrics_report.txt"
|
| 161 |
+
|
| 162 |
+
# ============== Step 3: analyze_results (好/坏样本可视化) ==============
|
| 163 |
+
echo "========================================"
|
| 164 |
+
echo "STEP 3: 好/坏样本可视化 (topk=${TOPK})"
|
| 165 |
+
echo "========================================"
|
| 166 |
+
|
| 167 |
+
"${PYTHON}" ${MMDET_DIR}/tools/analysis_tools/analyze_results.py \
|
| 168 |
+
"$CONFIG" \
|
| 169 |
+
"$PKL_FILE" \
|
| 170 |
+
"$ANALYZE_DIR" \
|
| 171 |
+
--topk $TOPK \
|
| 172 |
+
--show-score-thr $SCORE_THR \
|
| 173 |
+
--cfg-options launcher=none
|
| 174 |
+
|
| 175 |
+
echo ">>> 好样本保存到: ${ANALYZE_DIR}/good/"
|
| 176 |
+
echo ">>> 坏样本保存到: ${ANALYZE_DIR}/bad/"
|
| 177 |
+
|
| 178 |
+
# ============== Step 4: 混淆矩阵 ==============
|
| 179 |
+
echo "========================================"
|
| 180 |
+
echo "STEP 4: 生成混淆矩阵"
|
| 181 |
+
echo "========================================"
|
| 182 |
+
|
| 183 |
+
"${PYTHON}" ${MMDET_DIR}/tools/analysis_tools/confusion_matrix.py \
|
| 184 |
+
"$CONFIG" \
|
| 185 |
+
"$PKL_FILE" \
|
| 186 |
+
"$CM_DIR" \
|
| 187 |
+
--score-thr $SCORE_THR \
|
| 188 |
+
--tp-iou-thr 0.5
|
| 189 |
+
|
| 190 |
+
echo ">>> 混淆矩阵保存到: $CM_DIR"
|
| 191 |
+
|
| 192 |
+
echo ""
|
| 193 |
+
echo "========================================"
|
| 194 |
+
echo "全部完成! 结果目录结构:"
|
| 195 |
+
echo " ${OUTPUT_DIR}/"
|
| 196 |
+
echo " ├── predictions.pkl (推理结果)"
|
| 197 |
+
echo " ├── metrics_report.txt (Precision/Recall/F1)"
|
| 198 |
+
echo " ├── vis_images/ (检测可视化)"
|
| 199 |
+
echo " ├── analyze_results/ (好坏样本对比)"
|
| 200 |
+
echo " │ ├── good/ (检测效果好的样本)"
|
| 201 |
+
echo " │ └── bad/ (检测效果差的样本)"
|
| 202 |
+
echo " └── confusion_matrix/ (混淆矩阵)"
|
| 203 |
+
echo "========================================"
|
grounding-dino/run_eval_rex_style.sh
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -e
|
| 3 |
+
|
| 4 |
+
if [ -n "${PYTHON:-}" ]; then
|
| 5 |
+
PYTHON="${PYTHON}"
|
| 6 |
+
else
|
| 7 |
+
PYTHON="$(command -v python3 || true)"
|
| 8 |
+
fi
|
| 9 |
+
|
| 10 |
+
if [ -z "${PYTHON}" ]; then
|
| 11 |
+
echo "Error: python executable not found."
|
| 12 |
+
exit 1
|
| 13 |
+
fi
|
| 14 |
+
|
| 15 |
+
BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 16 |
+
MMDET_DIR="${BASE_DIR}/mmdetection"
|
| 17 |
+
PIP_INDEX_URL="${PIP_INDEX_URL:-https://pypi.tuna.tsinghua.edu.cn/simple}"
|
| 18 |
+
SETUP_ENV="${SETUP_ENV:-1}"
|
| 19 |
+
USE_VENV="${USE_VENV:-1}"
|
| 20 |
+
VENV_DIR="${VENV_DIR:-${BASE_DIR}/.eval_venv}"
|
| 21 |
+
INSTALL_OPENMIM="${INSTALL_OPENMIM:-0}"
|
| 22 |
+
HF_ENDPOINT_URL="${HF_ENDPOINT_URL:-https://hf-mirror.com}"
|
| 23 |
+
LOCAL_BERT_DIR="${LOCAL_BERT_DIR:-${BASE_DIR}/pretrained/hf/bert-base-uncased}"
|
| 24 |
+
HF_HOME_DIR="${HF_HOME_DIR:-${BASE_DIR}/.cache/huggingface}"
|
| 25 |
+
|
| 26 |
+
CONFIG="${CONFIG:-${BASE_DIR}/mmdetection/configs/mm_grounding_dino/grounding_dino_swin-t_finetune_traffic.py}"
|
| 27 |
+
CHECKPOINT="${CHECKPOINT:-$(cat ${BASE_DIR}/work_dirs/mm_grounding_dino_traffic/last_checkpoint)}"
|
| 28 |
+
OUTPUT_DIR="${OUTPUT_DIR:-${BASE_DIR}/eval_output_rex_style}"
|
| 29 |
+
|
| 30 |
+
PKL_FILE="${OUTPUT_DIR}/predictions.pkl"
|
| 31 |
+
JSONL_FILE="${OUTPUT_DIR}/predictions_rex_eval.jsonl"
|
| 32 |
+
REPORT_FILE="${OUTPUT_DIR}/rex_eval_results.txt"
|
| 33 |
+
VIS_DIR="${OUTPUT_DIR}/vis_images"
|
| 34 |
+
|
| 35 |
+
GPUS=${1:-1}
|
| 36 |
+
SCORE_THR="${SCORE_THR:-0.3}"
|
| 37 |
+
LARGE_IOU_THR="${LARGE_IOU_THR:-0.5}"
|
| 38 |
+
SMALL_IOU_THR="${SMALL_IOU_THR:-0.2}"
|
| 39 |
+
SIZE_THR="${SIZE_THR:-50}"
|
| 40 |
+
BATCH_SIZE="${BATCH_SIZE:-1}"
|
| 41 |
+
NUM_WORKERS="${NUM_WORKERS:-4}"
|
| 42 |
+
DISABLE_TF32="${DISABLE_TF32:-1}"
|
| 43 |
+
DEBUG_SYNC="${DEBUG_SYNC:-0}"
|
| 44 |
+
|
| 45 |
+
mkdir -p "${OUTPUT_DIR}" "${VIS_DIR}"
|
| 46 |
+
|
| 47 |
+
if [ "${USE_VENV}" = "1" ]; then
|
| 48 |
+
if [ ! -x "${VENV_DIR}/bin/python" ]; then
|
| 49 |
+
if [ "${SETUP_ENV}" = "1" ]; then
|
| 50 |
+
echo "Creating isolated venv: ${VENV_DIR}"
|
| 51 |
+
"${PYTHON}" -m venv "${VENV_DIR}" --system-site-packages
|
| 52 |
+
else
|
| 53 |
+
echo "Error: venv not found at ${VENV_DIR}. Run with SETUP_ENV=1 first."
|
| 54 |
+
exit 1
|
| 55 |
+
fi
|
| 56 |
+
fi
|
| 57 |
+
PYTHON="${VENV_DIR}/bin/python"
|
| 58 |
+
fi
|
| 59 |
+
|
| 60 |
+
if [ "${SETUP_ENV}" = "1" ]; then
|
| 61 |
+
echo "========================================"
|
| 62 |
+
echo "STEP 0: Rebuild evaluation environment"
|
| 63 |
+
echo "========================================"
|
| 64 |
+
echo "PYTHON(install): ${PYTHON}"
|
| 65 |
+
echo "PIP_INDEX_URL: ${PIP_INDEX_URL}"
|
| 66 |
+
echo "INSTALL_OPENMIM: ${INSTALL_OPENMIM}"
|
| 67 |
+
|
| 68 |
+
"${PYTHON}" -m pip install -U pip setuptools wheel packaging -i "${PIP_INDEX_URL}"
|
| 69 |
+
if [ "${INSTALL_OPENMIM}" = "1" ]; then
|
| 70 |
+
"${PYTHON}" -m pip install -U openmim -i "${PIP_INDEX_URL}"
|
| 71 |
+
fi
|
| 72 |
+
"${PYTHON}" -m pip install mmengine -i "${PIP_INDEX_URL}"
|
| 73 |
+
if ! "${PYTHON}" -m pip install "mmcv==2.1.0" --no-cache-dir -i "${PIP_INDEX_URL}"; then
|
| 74 |
+
echo "mmcv install failed, retry with --no-build-isolation (fix pkg_resources error)"
|
| 75 |
+
"${PYTHON}" -m pip install -U setuptools wheel packaging ninja Cython -i "${PIP_INDEX_URL}"
|
| 76 |
+
"${PYTHON}" -m pip install "mmcv==2.1.0" --no-cache-dir --no-build-isolation -i "${PIP_INDEX_URL}"
|
| 77 |
+
fi
|
| 78 |
+
|
| 79 |
+
cd "${MMDET_DIR}"
|
| 80 |
+
"${PYTHON}" -m pip install -r requirements/multimodal.txt -i "${PIP_INDEX_URL}"
|
| 81 |
+
"${PYTHON}" -m pip install -v -e . --no-build-isolation
|
| 82 |
+
|
| 83 |
+
"${PYTHON}" -m pip install --no-cache-dir --upgrade \
|
| 84 |
+
"opencv-python-headless==4.8.0.74" "numpy<2.0.0" "tqdm==4.67.1" "requests>=2.32.2" \
|
| 85 |
+
-i "${PIP_INDEX_URL}"
|
| 86 |
+
|
| 87 |
+
export HF_ENDPOINT="${HF_ENDPOINT_URL}"
|
| 88 |
+
export HF_HOME="${HF_HOME_DIR}"
|
| 89 |
+
export HUGGINGFACE_HUB_CACHE="${HF_HOME_DIR}/hub"
|
| 90 |
+
export TRANSFORMERS_CACHE="${HF_HOME_DIR}/hub"
|
| 91 |
+
export LOCAL_BERT_DIR
|
| 92 |
+
mkdir -p "${LOCAL_BERT_DIR}" "${HUGGINGFACE_HUB_CACHE}"
|
| 93 |
+
|
| 94 |
+
"${PYTHON}" - <<'PY'
|
| 95 |
+
import os
|
| 96 |
+
from pathlib import Path
|
| 97 |
+
from huggingface_hub import snapshot_download
|
| 98 |
+
|
| 99 |
+
repo_id = "bert-base-uncased"
|
| 100 |
+
local_dir = os.environ["LOCAL_BERT_DIR"]
|
| 101 |
+
snapshot_download(repo_id=repo_id, local_dir=local_dir)
|
| 102 |
+
|
| 103 |
+
required_files = ["config.json", "tokenizer_config.json", "vocab.txt"]
|
| 104 |
+
missing = [f for f in required_files if not Path(local_dir, f).exists()]
|
| 105 |
+
if missing:
|
| 106 |
+
raise SystemExit(f"Missing required files in local BERT dir: {missing}")
|
| 107 |
+
print("Local BERT files are ready.")
|
| 108 |
+
PY
|
| 109 |
+
|
| 110 |
+
export HF_HUB_OFFLINE=1
|
| 111 |
+
export TRANSFORMERS_OFFLINE=1
|
| 112 |
+
fi
|
| 113 |
+
|
| 114 |
+
echo "========================================"
|
| 115 |
+
echo "STEP 1: Run MMDetection test to export pkl"
|
| 116 |
+
echo "========================================"
|
| 117 |
+
echo "CONFIG: ${CONFIG}"
|
| 118 |
+
echo "CHECKPOINT: ${CHECKPOINT}"
|
| 119 |
+
echo "GPUS: ${GPUS}"
|
| 120 |
+
echo "OUTPUT_DIR: ${OUTPUT_DIR}"
|
| 121 |
+
echo "BATCH_SIZE: ${BATCH_SIZE}"
|
| 122 |
+
echo "NUM_WORKERS: ${NUM_WORKERS}"
|
| 123 |
+
|
| 124 |
+
if [ "${DISABLE_TF32}" = "1" ]; then
|
| 125 |
+
# TF32 can trigger unstable GEMM behavior on some torch/cuda combos.
|
| 126 |
+
export NVIDIA_TF32_OVERRIDE=0
|
| 127 |
+
export TORCH_ALLOW_TF32_CUBLAS_OVERRIDE=0
|
| 128 |
+
fi
|
| 129 |
+
if [ "${DEBUG_SYNC}" = "1" ]; then
|
| 130 |
+
export CUDA_LAUNCH_BLOCKING=1
|
| 131 |
+
fi
|
| 132 |
+
|
| 133 |
+
cd "${MMDET_DIR}"
|
| 134 |
+
|
| 135 |
+
run_test_once () {
|
| 136 |
+
local bs="$1"
|
| 137 |
+
local workers="$2"
|
| 138 |
+
|
| 139 |
+
if [ "${GPUS}" -eq 1 ]; then
|
| 140 |
+
"${PYTHON}" tools/test.py \
|
| 141 |
+
"${CONFIG}" \
|
| 142 |
+
"${CHECKPOINT}" \
|
| 143 |
+
--out "${PKL_FILE}" \
|
| 144 |
+
--show-dir "${VIS_DIR}" \
|
| 145 |
+
--cfg-options \
|
| 146 |
+
test_dataloader.batch_size="${bs}" \
|
| 147 |
+
test_dataloader.num_workers="${workers}" \
|
| 148 |
+
test_dataloader.persistent_workers=False
|
| 149 |
+
else
|
| 150 |
+
bash tools/dist_test.sh \
|
| 151 |
+
"${CONFIG}" \
|
| 152 |
+
"${CHECKPOINT}" \
|
| 153 |
+
"${GPUS}" \
|
| 154 |
+
--out "${PKL_FILE}" \
|
| 155 |
+
--show-dir "${VIS_DIR}" \
|
| 156 |
+
--cfg-options \
|
| 157 |
+
test_dataloader.batch_size="${bs}" \
|
| 158 |
+
test_dataloader.num_workers="${workers}" \
|
| 159 |
+
test_dataloader.persistent_workers=False
|
| 160 |
+
fi
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
if ! run_test_once "${BATCH_SIZE}" "${NUM_WORKERS}"; then
|
| 164 |
+
if [ "${BATCH_SIZE}" -ne 1 ]; then
|
| 165 |
+
echo "Primary test run failed, retry with safer settings (BATCH_SIZE=1, DEBUG_SYNC=1)."
|
| 166 |
+
export CUDA_LAUNCH_BLOCKING=1
|
| 167 |
+
run_test_once 1 2
|
| 168 |
+
else
|
| 169 |
+
exit 1
|
| 170 |
+
fi
|
| 171 |
+
fi
|
| 172 |
+
|
| 173 |
+
echo "========================================"
|
| 174 |
+
echo "STEP 2: Run Rex-Omni evaluate.py method"
|
| 175 |
+
echo "========================================"
|
| 176 |
+
|
| 177 |
+
PYTHONPATH="${MMDET_DIR}:${PYTHONPATH}" "${PYTHON}" "${BASE_DIR}/evaluate_with_rex_omni.py" \
|
| 178 |
+
--config "${CONFIG}" \
|
| 179 |
+
--pkl "${PKL_FILE}" \
|
| 180 |
+
--output-jsonl "${JSONL_FILE}" \
|
| 181 |
+
--output-report "${REPORT_FILE}" \
|
| 182 |
+
--score-thr "${SCORE_THR}" \
|
| 183 |
+
--large-iou-thr "${LARGE_IOU_THR}" \
|
| 184 |
+
--small-iou-thr "${SMALL_IOU_THR}" \
|
| 185 |
+
--size-thr "${SIZE_THR}"
|
| 186 |
+
|
| 187 |
+
echo "========================================"
|
| 188 |
+
echo "Done."
|
| 189 |
+
echo "PKL: ${PKL_FILE}"
|
| 190 |
+
echo "Rex JSONL: ${JSONL_FILE}"
|
| 191 |
+
echo "Rex report: ${REPORT_FILE}"
|
| 192 |
+
echo "VIS: ${VIS_DIR}"
|
| 193 |
+
echo "========================================"
|
grounding-dino/run_train.sh
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -e # 遇到错误立即停止
|
| 3 |
+
set -x # 打印调试信息
|
| 4 |
+
|
| 5 |
+
# ================= 配置区域 =================
|
| 6 |
+
BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 7 |
+
if [ -n "${PYTHON:-}" ]; then
|
| 8 |
+
PYTHON="${PYTHON}"
|
| 9 |
+
elif command -v python3 >/dev/null 2>&1; then
|
| 10 |
+
PYTHON="$(command -v python3)"
|
| 11 |
+
else
|
| 12 |
+
PYTHON="$(command -v python)"
|
| 13 |
+
fi
|
| 14 |
+
PIP="${PYTHON} -m pip"
|
| 15 |
+
MMDET_DIR="${BASE_DIR}/mmdetection"
|
| 16 |
+
CONFIG_FILE="${MMDET_DIR}/configs/grounding_dino/my_swin_b_finetune.py"
|
| 17 |
+
GPUS=2
|
| 18 |
+
# ===========================================
|
| 19 |
+
|
| 20 |
+
echo "========================================"
|
| 21 |
+
echo "STEP 1: 暴力清理 (清空所有相关库)"
|
| 22 |
+
echo "========================================"
|
| 23 |
+
|
| 24 |
+
# 卸载所有涉及的库
|
| 25 |
+
$PIP uninstall mmdet mmcv mmcv-full mmengine -y || true
|
| 26 |
+
$PIP uninstall opencv-python opencv-python-headless opencv-contrib-python -y || true
|
| 27 |
+
$PIP uninstall opencv-python opencv-python-headless opencv-contrib-python -y || true
|
| 28 |
+
$PIP uninstall numpy -y || true
|
| 29 |
+
|
| 30 |
+
# 物理删除残留
|
| 31 |
+
SITE_PACKAGES=$($PYTHON -c "import site; print(site.getsitepackages()[0])")
|
| 32 |
+
rm -rf "${SITE_PACKAGES}/cv2"
|
| 33 |
+
rm -rf "${SITE_PACKAGES}/opencv*"
|
| 34 |
+
rm -rf "${SITE_PACKAGES}/numpy*"
|
| 35 |
+
rm -rf "${SITE_PACKAGES}/mmcv*"
|
| 36 |
+
|
| 37 |
+
echo "========================================"
|
| 38 |
+
echo "STEP 2: 安装 MM 基础库 (锁定兼容版本)"
|
| 39 |
+
echo "========================================"
|
| 40 |
+
|
| 41 |
+
# 安装基础引擎
|
| 42 |
+
$PIP install -U openmim -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 43 |
+
$PIP install mmengine -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 44 |
+
|
| 45 |
+
# 【关键修改】显式安装 2.1.0 版本,避开 incompatible 报错
|
| 46 |
+
# 使用 --no-cache-dir 防止缓存干扰
|
| 47 |
+
$PIP install "mmcv==2.1.0" --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 48 |
+
|
| 49 |
+
echo "========================================"
|
| 50 |
+
echo "STEP 3: 安装 MMDetection"
|
| 51 |
+
echo "========================================"
|
| 52 |
+
|
| 53 |
+
cd "$MMDET_DIR"
|
| 54 |
+
$PIP install -r requirements/multimodal.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 55 |
+
$PIP install -v -e .
|
| 56 |
+
|
| 57 |
+
echo "========================================"
|
| 58 |
+
echo "STEP 4: 环境强制修复 (解决 OpenCV 和 NumPy)"
|
| 59 |
+
echo "========================================"
|
| 60 |
+
|
| 61 |
+
echo "正在剔除冲突库..."
|
| 62 |
+
# 1. 卸载可能被自动安装的标准版 OpenCV
|
| 63 |
+
$PIP uninstall opencv-python opencv-contrib-python -y || true
|
| 64 |
+
$PIP uninstall opencv-python-headless -y || true
|
| 65 |
+
|
| 66 |
+
echo "正在锁定正确版本..."
|
| 67 |
+
# 2. 安装 Headless OpenCV
|
| 68 |
+
$PIP install opencv-python-headless==4.8.0.74 --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 69 |
+
|
| 70 |
+
# 3. 强制重装 NumPy 1.x (解决 import error)
|
| 71 |
+
$PIP install "numpy<2.0.0" --force-reinstall -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 72 |
+
|
| 73 |
+
echo "========================================"
|
| 74 |
+
echo "STEP 5: 最终验证 & 启动"
|
| 75 |
+
echo "========================================"
|
| 76 |
+
|
| 77 |
+
# 验证 NumPy 版本
|
| 78 |
+
$PYTHON -c "import numpy; print(f'>>> Current NumPy Version: {numpy.__version__}'); assert int(numpy.__version__.split('.')[0]) < 2"
|
| 79 |
+
# 验证 OpenCV
|
| 80 |
+
$PYTHON -c "import cv2; print(f'>>> Current OpenCV Version: {cv2.__version__}')"
|
| 81 |
+
# 验证 MMCV 版本
|
| 82 |
+
$PYTHON -c "import mmcv; print(f'>>> Current MMCV Version: {mmcv.__version__}')"
|
| 83 |
+
|
| 84 |
+
# 启动训练
|
| 85 |
+
export OPENCV_HEADLESS=1
|
| 86 |
+
bash "${MMDET_DIR}/tools/dist_train.sh" "${MMDET_DIR}/configs/grounding_dino/grounding_dino_swin-b_mydata.py" "${GPUS}"
|
grounding-dino/train_mm_grounding_dino.sh
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -e # 遇到错误立即停止
|
| 3 |
+
set -x # 打印调试信息
|
| 4 |
+
|
| 5 |
+
# ================= 配置区域 =================
|
| 6 |
+
BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 7 |
+
if [ -n "${PYTHON:-}" ]; then
|
| 8 |
+
PYTHON="${PYTHON}"
|
| 9 |
+
elif command -v python3 >/dev/null 2>&1; then
|
| 10 |
+
PYTHON="$(command -v python3)"
|
| 11 |
+
else
|
| 12 |
+
PYTHON="$(command -v python)"
|
| 13 |
+
fi
|
| 14 |
+
PIP="${PYTHON} -m pip"
|
| 15 |
+
MMDET_DIR="${BASE_DIR}/mmdetection"
|
| 16 |
+
CONFIG_FILE="${MMDET_DIR}/configs/grounding_dino/my_swin_b_finetune.py"
|
| 17 |
+
GPUS=1
|
| 18 |
+
HF_ENDPOINT_URL="${HF_ENDPOINT_URL:-https://hf-mirror.com}"
|
| 19 |
+
LOCAL_BERT_DIR="${LOCAL_BERT_DIR:-${BASE_DIR}/pretrained/hf/bert-base-uncased}"
|
| 20 |
+
HF_HOME_DIR="${HF_HOME_DIR:-${BASE_DIR}/.cache/huggingface}"
|
| 21 |
+
# ===========================================
|
| 22 |
+
|
| 23 |
+
echo "========================================"
|
| 24 |
+
echo "STEP 1: 暴力清理 (清空所有相关库)"
|
| 25 |
+
echo "========================================"
|
| 26 |
+
|
| 27 |
+
# 卸载所有涉及的库
|
| 28 |
+
$PIP uninstall mmdet mmcv mmcv-full mmengine -y || true
|
| 29 |
+
$PIP uninstall opencv-python opencv-python-headless opencv-contrib-python -y || true
|
| 30 |
+
$PIP uninstall opencv-python opencv-python-headless opencv-contrib-python -y || true
|
| 31 |
+
$PIP uninstall numpy -y || true
|
| 32 |
+
$PIP uninstall tqdm requests -y || true
|
| 33 |
+
|
| 34 |
+
# 物理删除残留
|
| 35 |
+
SITE_PACKAGES=$($PYTHON -c "import site; print(site.getsitepackages()[0])")
|
| 36 |
+
rm -rf "${SITE_PACKAGES}/cv2"
|
| 37 |
+
rm -rf "${SITE_PACKAGES}/opencv*"
|
| 38 |
+
rm -rf "${SITE_PACKAGES}/numpy*"
|
| 39 |
+
rm -rf "${SITE_PACKAGES}/mmcv*"
|
| 40 |
+
rm -rf "${SITE_PACKAGES}/tqdm" "${SITE_PACKAGES}/tqdm-"*.dist-info
|
| 41 |
+
|
| 42 |
+
echo "========================================"
|
| 43 |
+
echo "STEP 2: 安装 MM 基础库 (锁定兼容版本)"
|
| 44 |
+
echo "========================================"
|
| 45 |
+
|
| 46 |
+
# 安装基础引擎
|
| 47 |
+
$PIP install -U openmim -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 48 |
+
$PIP install mmengine -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 49 |
+
|
| 50 |
+
# 【关键修改】显式安装 2.1.0 版本,避开 incompatible 报错
|
| 51 |
+
# 使用 --no-cache-dir 防止缓存干扰
|
| 52 |
+
$PIP install "mmcv==2.1.0" --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 53 |
+
|
| 54 |
+
echo "========================================"
|
| 55 |
+
echo "STEP 3: 安装 MMDetection"
|
| 56 |
+
echo "========================================"
|
| 57 |
+
|
| 58 |
+
cd "$MMDET_DIR"
|
| 59 |
+
$PIP install -r requirements/multimodal.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 60 |
+
$PIP install -v -e .
|
| 61 |
+
|
| 62 |
+
echo "========================================"
|
| 63 |
+
echo "STEP 4: 环境强制修复 (解决 OpenCV 和 NumPy)"
|
| 64 |
+
echo "========================================"
|
| 65 |
+
|
| 66 |
+
echo "正在剔除冲突库..."
|
| 67 |
+
# 1. 卸载可能被自动安装的标准版 OpenCV
|
| 68 |
+
$PIP uninstall opencv-python opencv-contrib-python -y || true
|
| 69 |
+
$PIP uninstall opencv-python-headless -y || true
|
| 70 |
+
|
| 71 |
+
echo "正在锁定正确版本..."
|
| 72 |
+
# 2. 安装 Headless OpenCV
|
| 73 |
+
$PIP install opencv-python-headless==4.8.0.74 --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 74 |
+
|
| 75 |
+
# 3. 强制重装 NumPy 1.x (解决 import error)
|
| 76 |
+
$PIP install "numpy<2.0.0" --force-reinstall -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 77 |
+
|
| 78 |
+
# 4. 修复 tqdm 元数据损坏 (解决 transformers 检查版本失败)
|
| 79 |
+
$PIP install --no-cache-dir --force-reinstall "tqdm==4.67.1" "requests>=2.32.2" -i https://pypi.tuna.tsinghua.edu.cn/simple
|
| 80 |
+
|
| 81 |
+
echo "========================================"
|
| 82 |
+
echo "STEP 5: 使用 HF 国内镜像下载 BERT 到本地"
|
| 83 |
+
echo "========================================"
|
| 84 |
+
|
| 85 |
+
export HF_ENDPOINT="$HF_ENDPOINT_URL"
|
| 86 |
+
export HF_HOME="$HF_HOME_DIR"
|
| 87 |
+
export HUGGINGFACE_HUB_CACHE="${HF_HOME_DIR}/hub"
|
| 88 |
+
export TRANSFORMERS_CACHE="${HF_HOME_DIR}/hub"
|
| 89 |
+
export LOCAL_BERT_DIR
|
| 90 |
+
mkdir -p "$LOCAL_BERT_DIR" "$HUGGINGFACE_HUB_CACHE"
|
| 91 |
+
|
| 92 |
+
$PYTHON - <<'PY'
|
| 93 |
+
import os
|
| 94 |
+
from pathlib import Path
|
| 95 |
+
from huggingface_hub import snapshot_download
|
| 96 |
+
|
| 97 |
+
repo_id = "bert-base-uncased"
|
| 98 |
+
local_dir = os.environ["LOCAL_BERT_DIR"]
|
| 99 |
+
|
| 100 |
+
print(f">>> HF endpoint: {os.environ.get('HF_ENDPOINT')}")
|
| 101 |
+
print(f">>> Downloading {repo_id} to: {local_dir}")
|
| 102 |
+
snapshot_download(repo_id=repo_id, local_dir=local_dir)
|
| 103 |
+
|
| 104 |
+
required_files = [
|
| 105 |
+
"config.json",
|
| 106 |
+
"tokenizer_config.json",
|
| 107 |
+
"vocab.txt",
|
| 108 |
+
]
|
| 109 |
+
missing = [f for f in required_files if not Path(local_dir, f).exists()]
|
| 110 |
+
if missing:
|
| 111 |
+
raise SystemExit(f"Missing required files in local BERT dir: {missing}")
|
| 112 |
+
|
| 113 |
+
print(">>> Local BERT files are ready.")
|
| 114 |
+
PY
|
| 115 |
+
|
| 116 |
+
# 下载完成后强制离线,避免训练过程访问外网重试
|
| 117 |
+
export HF_HUB_OFFLINE=1
|
| 118 |
+
export TRANSFORMERS_OFFLINE=1
|
| 119 |
+
|
| 120 |
+
# echo "========================================"
|
| 121 |
+
# echo "STEP 6: 最终验证 & 启动"
|
| 122 |
+
# echo "========================================"
|
| 123 |
+
|
| 124 |
+
# # 验证 NumPy 版本
|
| 125 |
+
# $PYTHON -c "import numpy; print(f'>>> Current NumPy Version: {numpy.__version__}'); assert int(numpy.__version__.split('.')[0]) < 2"
|
| 126 |
+
# # 验证 OpenCV
|
| 127 |
+
# $PYTHON -c "import cv2; print(f'>>> Current OpenCV Version: {cv2.__version__}')"
|
| 128 |
+
# # 验证 MMCV 版本
|
| 129 |
+
# $PYTHON -c "import mmcv; print(f'>>> Current MMCV Version: {mmcv.__version__}')"
|
| 130 |
+
|
| 131 |
+
# ================= 开始训练脚本 =================
|
| 132 |
+
# ================= 配置区域 =================
|
| 133 |
+
MMDET_DIR="${BASE_DIR}/mmdetection"
|
| 134 |
+
CONFIG_FILE="${MMDET_DIR}/configs/mm_grounding_dino/grounding_dino_swin-t_finetune_traffic.py"
|
| 135 |
+
WORK_DIR="${BASE_DIR}/work_dirs/mm_grounding_dino_traffic"
|
| 136 |
+
GPUS=${1:-4} # 默认使用 4 卡,可通过参数指定
|
| 137 |
+
|
| 138 |
+
# ================= 环境检查 =================
|
| 139 |
+
echo "========================================"
|
| 140 |
+
echo "环境检查"
|
| 141 |
+
echo "========================================"
|
| 142 |
+
|
| 143 |
+
# 检查 Python 和依赖
|
| 144 |
+
$PYTHON -c "import importlib.metadata as m; print(f'tqdm version: {m.version(\"tqdm\")}')"
|
| 145 |
+
$PYTHON -c "import mmdet; print(f'MMDetection version: {mmdet.__version__}')"
|
| 146 |
+
$PYTHON -c "import mmcv; print(f'MMCV version: {mmcv.__version__}')"
|
| 147 |
+
$PYTHON -c "import torch; print(f'PyTorch version: {torch.__version__}')"
|
| 148 |
+
$PYTHON -c "import torch; print(f'CUDA available: {torch.cuda.is_available()}')"
|
| 149 |
+
$PYTHON -c "import torch; print(f'CUDA device count: {torch.cuda.device_count()}')"
|
| 150 |
+
$PYTHON -c "from transformers import AutoTokenizer; AutoTokenizer.from_pretrained('${LOCAL_BERT_DIR}', local_files_only=True); print('Local BERT tokenizer check: OK')"
|
| 151 |
+
|
| 152 |
+
# ================= 开始训练 =================
|
| 153 |
+
echo "========================================"
|
| 154 |
+
echo "开始训练 MM-Grounding DINO"
|
| 155 |
+
echo "配置文件: ${CONFIG_FILE}"
|
| 156 |
+
echo "工作目录: ${WORK_DIR}"
|
| 157 |
+
echo "GPU 数量: ${GPUS}"
|
| 158 |
+
echo "========================================"
|
| 159 |
+
|
| 160 |
+
cd "$MMDET_DIR"
|
| 161 |
+
|
| 162 |
+
# 单卡训练
|
| 163 |
+
if [ "$GPUS" -eq 1 ]; then
|
| 164 |
+
"$PYTHON" tools/train.py "${CONFIG_FILE}" \
|
| 165 |
+
--work-dir "${WORK_DIR}" \
|
| 166 |
+
--cfg-options lang_model_name="${LOCAL_BERT_DIR}" model.language_model.name="${LOCAL_BERT_DIR}"
|
| 167 |
+
# 多卡分布式训练
|
| 168 |
+
else
|
| 169 |
+
PYTHON="$PYTHON" bash tools/dist_train.sh "${CONFIG_FILE}" "${GPUS}" \
|
| 170 |
+
--work-dir "${WORK_DIR}" \
|
| 171 |
+
--cfg-options lang_model_name="${LOCAL_BERT_DIR}" model.language_model.name="${LOCAL_BERT_DIR}"
|
| 172 |
+
fi
|
| 173 |
+
|
| 174 |
+
echo "========================================"
|
| 175 |
+
echo "训练完成!"
|
| 176 |
+
echo "模型保存在: ${WORK_DIR}"
|
| 177 |
+
echo "========================================"
|